序列化二叉树

# 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()


上一篇:43. 字符串相乘


下一篇:python 矩阵操作--->>np.column_stack用法