边工作边刷题:70天一遍leetcode: day 54

Serialize and Deserialize Binary Tree

要点:preorder traversal,node allocation是在function里:意思是如果有一个新值,那么allocate一个node,同时因为python不支持pass-by-reference,所以left/right连接要在返回值做。
错误点:

  • serialize的时候不要忘了delimiter
  • deserialize要用一个nonlocal variable i表示当前已经处理到的元素,因为python只有pass-by-value,如果不是nonlocal,i+=1只对同层的i递增。注意一旦赋值,会有一个新的local。
  • python 3.0用nonlocal来表示not function local variable,python 2.x用i=[0],因为list元素assignment不是variable assignment,所以不会变成local
  • 也可以用返回值,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
        """
        def serial(root, res):
            if not root:
                res.append("#")
                return
            res.append(str(root.val))
            serial(root.left, res)
            serial(root.right, res)
        
        res = []
        serial(root, res)
        # print res
        return ",".join(res)

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        i=[0]
        def deserial(data):
            # nonlocal i
            # print i[0]
            if data[i[0]]=="#":
                return None
            
            root = TreeNode(data[i[0]])
            i[0]+=1
            if i[0]<len(data):
                root.left = deserial(data)
            i[0]+=1
            if i[0]<len(data):
                root.right = deserial(data)
            return root
        
        data = data.split(",")
        return deserial(data)

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

posted @ 2016-06-19 04:26  absolute100  阅读(147)  评论(0编辑  收藏  举报