LeetCode笔记

二叉树的序列化和反序列化

2018-03-20  本文已影响20人  只为此心无垠
def serialize(self, root):
        if root == None:
            return None
        result = []
        queue = [root]
        
        while len(queue) == 0:
            curNode = queue.pop(0)
            if curNode:
                result.append(curNode.val)
                queue.append(curNode.left)
                queue.append(curNode.right)
            else:
                result.append('#')
            
        return result

def deserialize(self, data):
        # write your code here
        if len(data) == 0:
            return None
        root = TreeNode(data[0])
        
        queue = [root]
        index = 0
        while index+1 < len(data):
            curNode = queue.pop(0)
            if curNode:
                left = TreeNode(data[index+1])
                right = TreeNode(data[index+2])
                if data[index+1] == '#':
                    left = None
                if data[index+2] == '#':
                    right = None
                index += 2
                queue.append(left)
                queue.append(right)
                curNode.left = left
                curNode.right = right
        return root
上一篇 下一篇

猜你喜欢

热点阅读