Serialize and Deserialize Binary Tree

这题理论上来说,前序中序后序层级都是可以实现序列化和反序列化的,但是中序和后序本身就不是很好实现更妄论序列化问题了,前序因为本身就符合栈的顺序相对比较好做,另外BFS利用队列也是可行的

这里前序的方法需要两个额外变量parent和pointer,parent记录当前前序的父节点,我们需要通过parent来连接当前的新节点,而pointer则用来判定当前这个孩子是左孩子还是右孩子,每当点不为空点时,pointer需要调整为指向左,parent变为当前新节点,当结点为空时,将栈中弹出的结点设为parent,pointer指向右,最后因为空节点的数量永远比节点数大一,所以可能会出现空栈弹出的问题,加一个if语句判断一下

# 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 ''

        stack = [root]
        result = []
        while stack:
            node = stack.pop()
            if node:
                result.append(`node.val`)
                stack.append(node.right)
                stack.append(node.left)
            else:
                result.append('#')

        return '+'.join(result)

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

        :type data: str
        :rtype: TreeNode
        """
        if not data:
            return None

        nodes = data.split('+')
        result = TreeNode(int(nodes[0]))
        parent, pointer = result, 1
        stack = [result]

        for i in xrange(1, len(nodes)):
            if nodes[i] != '#':
                tmp = TreeNode(int(nodes[i]))
                if pointer:
                    parent.left = tmp
                else:
                    parent.right = tmp
                parent = tmp
                stack.append(parent)
                pointer = 1
            else:
                if not stack:
                    return result
                parent = stack.pop()
                pointer = 0

        return result

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

还可以继续研究一下BFS,个人感觉还算好实现

results matching ""

    No results matching ""