其他分享
首页 > 其他分享> > 序列化二叉树

序列化二叉树

作者:互联网

# 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
        """
        vals = []
        def encode(root):
            if not root:
                vals.append('null')
                return
                
            vals.append(str(root.val))
            encode(root.left)
            encode(root.right)
        
        encode(root)
        return '[' + ','.join(vals) + ']'
        

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        vals = iter(data[1:-1].split(','))
        def decode():
            val = next(vals)
            if val == 'null':
                return
            
            node = TreeNode(val)
            node.left = decode()
            node.right = decode()
            return node
        
        return decode()


标签:node,return,val,self,二叉树,vals,序列化,root
来源: https://www.cnblogs.com/KbMan/p/14498908.html