加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

lc 297. Serialize and Deserialize Binary Tree

发布时间:2020-12-14 04:35:06 所属栏目:大数据 来源:网络整理
导读:使用任意方法序列化一个二叉树。 https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ 原来带有None作为结束标志的x序遍历的结果是可以唯一的恢复一颗二叉树的!!! 如果没有None结束标记,是无法做到的! 代码没法子讲,自己看吧。 如

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

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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读