lc 297. Serialize and Deserialize Binary Tree

使用任意方法序列化一个二叉树。

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/

原来带有None作为结束标志的x序遍历的结果是可以唯一的恢复一颗二叉树的!!!

如果没有None结束标记,是无法做到的!

代码没法子讲,自己看吧。

如何快速打印?先print(serialize),再print(serialize(deserialize(serialize(root))))

 1 class Codec:
 2 
 3     def serialize(self, root):
 4         """Encodes a tree to a single string.
 5 
 6         :type root: TreeNode
 7         :rtype: str
 8         """
 9         def rec(root):
10             if root==None:
11                 return 'None,'
12             return str(root.val)+','+rec(root.left)+rec(root.right)
13         return rec(root)
14 
15     def deserialize(self, data):
16         """Decodes your encoded data to tree.
17 
18         :type data: str
19         :rtype: TreeNode
20         """
21         def rec(start):
22             i=start
23             while data[i]!=',':
24                 i+=1
25             if i-start==4 and data[start:i]=='None':
26                 return None,start+5
27             # print(data[start:i],'to trans')
28             node=TreeNode(int(data[start:i]))
29             l,ls=rec(i+1)
30             r,rs=rec(ls)
31             node.left=l
32             node.right=r
33             return node,rs
34         return rec(0)[0]

 

posted @ 2019-04-03 18:23  Cloud.9  阅读(208)  评论(0编辑  收藏  举报