剑指 Offer 37. 序列化二叉树(python)

题目链接

请实现两个函数,分别用来序列化和反序列化二叉树。

示例:

你可以将以下二叉树:

1

/
2 3
/
4 5

序列化为 “[1,2,3,null,null,4,5]”

解题思路:

在反序列化的过程中,也要按照queue作为判断条件,不能按照给的data进行循环,不然在queue中有多个null的时候没法处理

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        if not root: return "[]"
        stack=[root]
        res=[]
        while stack:
            node=stack.pop(0)
            if node:
                res.append(str(node.val))
                stack.append(node.left)
                stack.append(node.right)
            else:
                res.append("null")
        return '['+','.join(res)+']'

    
    def deserialize(self, data):
        if data == "[]": return
        vals, i = data[1:-1].split(','), 1
        root = TreeNode(int(vals[0]))
        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 += 1
            if vals[i] != "null":
                node.right = TreeNode(int(vals[i]))
                queue.append(node.right)
            i += 1
        return root

你可能感兴趣的:(leetcode)