Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bug][python] xu-lie-hua-er-cha-shu-lcof #1363

Open
1 of 2 tasks
labuladong opened this issue Mar 26, 2023 · 1 comment
Open
1 of 2 tasks

[bug][python] xu-lie-hua-er-cha-shu-lcof #1363

labuladong opened this issue Mar 26, 2023 · 1 comment
Labels
help wanted Extra attention is needed

Comments

@labuladong
Copy link
Owner

此 issue 的目的是修复 chatGPT 转译的多语言代码,更详细的背景信息和修复流程见:#1113

请在提交 bug 之前先搜索

  • 我已经搜索过 issues,没有发现相同的 bug。

出错的题目链接

https://leetcode.cn/problems/xu-lie-hua-er-cha-shu-lcof/

报错信息

Line 19: AttributeError: 'NoneType' object has no attribute 'append'
AttributeError: 'NoneType' object has no attribute 'append'
    sb.append(str(root.val)).append(self.SEP)
Line 19 in _serialize (Solution.py)
    self._serialize(root, sb)
Line 9 in serialize (Solution.py)
    return codec.deserialize(codec.serialize(root))
Line 48 in __helper__ (Solution.py)
    ret = __DriverSolution__().__helper__(
Line 61 in _driver (Solution.py)
    _driver()
Line 73 in <module> (Solution.py)

你是否愿意提交 PR 修复这个 bug?

  • 我愿意!
@labuladong labuladong added the help wanted Extra attention is needed label Mar 26, 2023
@sucst
Copy link

sucst commented Apr 16, 2023

#根据题目示例中的例子,序列化结果为vals=[1,2,3,null,null,4,5,null,null,null,null],对应到二叉树中,根节点为1,其左右子节点为2,3,序列中对应序号为1,2
'''
1.创建一个队列queue,初始时只有根节点,表示当前处理到的节点。
2.初始化一个序列下标,从1开始。
3.取出队列中第一个节点node,i对应的如果不为空,则说明val=vals[i]的节点为node的左子节点,将node.left加入队列。i后移一位,同样如果vals[i]不为空,则对应node的右子节点,node.right加入队列。
'''
class Codec:

def serialize(self, root):
    if not root:
        return "[]"
    queue = collections.deque()
    queue.append(root)
    result = []
    while queue:
        node = queue.popleft()
        if node != None:
            result.append(str(node.val))
            queue.append(node.left)
            queue.append(node.right)
        else:
            result.append("null")
    return '[' + ','.join(result) + ']'

def deserialize(self, data):
    if data == "[]":
        return
    vals = data[1:-1].split(',')
    root = TreeNode((int(vals[0])))
    i = 1
    queue = collections.deque()
    queue.append(root)
    while queue:
        node = queue.popleft()
        if vals[i] != "null":
            node.left = TreeNode(int(vals[i]))
            queue.append(node.left)
        i = i + 1
        if vals[i] != "null":
            node.right = TreeNode(int(vals[i]))
            queue.append(node.right)
        i = i + 1
    return root

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants