题目
分析
可以使用先序遍历和深度优先遍历序列化树,然后再逆过程反序列化
python代码
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Serialize(self, root):
# write code here
if not root: return ""
res = []
arr = [root]
while(len(arr)!=0):
temp_arr = []
for n in arr:
res.append(str(n.val) if n else "#")
if n:
temp_arr.append(n.left)
temp_arr.append(n.right)
arr = temp_arr
return "!".join(res)
def Deserialize(self, s):
# write code here
if len(s)==0: return None
vals = s.split("!")
root = TreeNode( int(vals[0]) if vals[0]!="#" else None)
arr = [root]
vals = vals[1:]
while(len(arr)!=0):
n = arr.pop(0)
left_val = vals.pop(0)
if left_val!="#":
left = TreeNode(int(left_val))
arr.append(left)
else:
left = None
n.left = left
right_val = vals.pop(0)
if right_val!="#":
right = TreeNode(int(right_val))
arr.append(right)
else:
right = None
n.right = right
return root