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

示例: 

你可以将以下二叉树:

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

Python 解答:这里没换成字符输出

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        if not root:
            return []
        queue = [root]
        res = []
        while queue:
            temp = queue.pop(0)
            if temp:
                res.append(temp.val)
                if temp.left:
                    queue.append(temp.left)
                else:
                    queue.append(None)
                if temp.right:
                    queue.append(temp.right)
                else:
                    queue.append(None)
            else:
                res.append(None)
        j = len(res)-1
        while res[j] == None:
            j -= 1
        return res[:j+1]

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        if not data:
            return None
        else:
            root = TreeNode(data.pop(0))
            queue = [root]
            while data:
                node = queue.pop(0)
                if data:
                    left = data.pop(0)
                    if left != None:
                        left = TreeNode(left)
                        queue.append(left)
                    node.left = left 
                if data:
                    right = data.pop(0)                
                    if right != None:
                        right = TreeNode(right)
                        queue.append(right)
                    node.right = right
        return root        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
最后修改日期: 2021年4月7日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。