Leetcode练习:二叉树的序列化与反序列化

采用逐层遍历的方式。

我的成绩:

执行用时 :108 ms, 在所有 Python 提交中击败了98.83% 的用户

内存消耗 :21.8 MB, 在所有 Python 提交中击败了36.72%的用户

代码如下:

# 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 []
        return_list = []
        current_level = [root]
        while(len(current_level)):
            new_level = []
            for current_node in current_level:
                if current_node:
                    return_list.append(str(current_node.val))
                    new_level.append(current_node.left)
                    new_level.append(current_node.right)
                else:
                    return_list.append(None)
            current_level = new_level
        
        return return_list

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        if len(data) == 0:
            return None
        return_node = TreeNode(int(data[0]))
        current_level = [return_node]
        data = data[1:]
        
        while(len(current_level)):
            new_level = []
            
            count = 0
            for current_node in current_level:
                if current_node:
                    count +=1
            if not count:
                break
            new_level_data = data[:count*2]
            data = data[count*2:]
            count = 0
            for current_node in current_level:
                if current_node:
                    if new_level_data[count]:
                        current_node.left = TreeNode(int(new_level_data[count]))
                    count += 1
                    new_level.append(current_node.left)
                    if new_level_data[count]:
                        current_node.right = TreeNode(int(new_level_data[count]))
                    count += 1
                    new_level.append(current_node.right)
            
            current_level = new_level
        
        return return_node
            
            
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))

 

你可能感兴趣的:(Leetcode练习,python初步)