• 边工作边刷题: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))
    
    
  • 相关阅读:
    mybatis-generator自动生成代码时,只生成insert方法
    elasticsearch-head-master下运行npm install报npm WARN elasticsearch-head@0.0.0 license should be a valid SPDX license expression
    fs.default.name和fs.defaultFS
    zookeeper集群为什么要是单数
    Quorom机制
    把数据库放入Docker是一个好主意吗?
    JVM GC算法CMS详解
    JVM之——CMS
    对于TCP/IP协议的三次握手和四次挥手的理解
    JVM G1和CMS
  • 原文地址:https://www.cnblogs.com/absolute/p/5690318.html
Copyright © 2020-2023  润新知