Careercup - Google面试题 - 5765091433644032

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?

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

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

代码:

 // http://www.careercup.com/question?id=5765091433644032
// Transfer a binary tree to another machine? Of course, serialization and deserialization.
// Any kind of tree traversal with the help of a special notation to represent 'NULL' can do the serialization.
// For example, preorder traversal for the tree below:
// 1
// / \
// 2 8
// / \ / \
// 7 12 34 9
//
// If we use '#' to represent NULL, the preorder traversal looks like {1, 2, 7, #, #, 12, #, #, 8, 34, #, #, 9, #, #}
// With this you can output the array to a text file.
// The '#' notation ensures that every binary tree has its unique preorder traversal.
int main()
{
return ;
}
上一篇:Spring Data Jpa接口简介


下一篇:Bootstrap Bootstrap表格插件bootstrap-table配置与应用小结