随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-05-08 09:32

题目链接

原题:

Given a binary tree, how would you copy it from one machine to the other, assume you have a flash drive. I believe we should write the binary tree to file and have the other machine de-serialize it. But how should we do it?

题目:如何序列化和反序列化一颗二叉树。

解法:做法当然有很多种,但基本都是基于某种遍历方式去进行文本或者二进制的表示。文本比较直观,不过二进制的序列化应该在空间上更有效率。我的思路是前序遍历,并用一个特殊符号来标记空指针。用括号来表示一颗完整的树,这样就能递归进行序列化/反序列化了。好像之前刚做了个一样的题,所以这题没有写代码。

代码:

复制代码
 1 // http://www.careercup.com/question?id=5765091433644032
 2 // Transfer a binary tree to another machine? Of course, serialization and deserialization.
 3 // Any kind of tree traversal with the help of a special notation to represent 'NULL' can do the serialization.
 4 // For example, preorder traversal for the tree below:
 5 //               1
 6 //             /   \
 7 //            2     8
 8 //           / \   / \
 9 //          7  12 34  9
10 //
11 // If we use '#' to represent NULL, the preorder traversal looks like {1, 2, 7, #, #, 12, #, #, 8, 34, #, #, 9, #, #}
12 // With this you can output the array to a text file.
13 // The '#' notation ensures that every binary tree has its unique preorder traversal.
14 int main()
15 {
16     return 0;
17 }
复制代码

 

 posted on   zhuli19901106  阅读(207)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示