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]

 

转载于:https://www.cnblogs.com/waldenlake/p/10650710.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值