Leetcode 449.序列化和反序列化二叉搜索树
1 题目描述(Leetcode题目链接)
序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。
设计一个算法来序列化和反序列化二叉搜索树。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。
编码的字符串应尽可能紧凑。
注意:不要使用类成员/全局/静态变量来存储状态。 你的序列化和反序列化算法应该是无状态的。
2 题解
就是先序遍历和中序遍历,与105题差不多的。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string.
"""
def preorder(root):
res = []
if root:
res.append(str(root.val))
res += preorder(root.left)
res += preorder(root.right)
return res
pre = preorder(root)
return ",".join(pre)
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree.
"""
if not data:
return None
preorder = [int(i) for i in data.split(',')]
inorder = sorted(preorder)
def buildtree(pre, ino):
if not ino:
return None
root = TreeNode(pre[0])
i = ino.index(pre[0])
root.left = buildtree(pre[1:i+1], ino[:i])
root.right = buildtree(pre[1+i:], ino[i+1:])
return root
return buildtree(preorder, inorder)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))