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 2014-05-08 10:01  zhuli19901106  阅读(204)  评论(0编辑  收藏  举报