zoukankan      html  css  js  c++  java
  • Careercup

    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 }
  • 相关阅读:
    C++的初始化成员列表
    C++的默认构造函数
    C++编译器将自动为类产生四个缺省的函数
    JS DOM
    Linux 打印简单日志(一)
    Linux 简单打印日志(二)
    可变参数输出(三)
    1110 Complete Binary Tree (25 分)
    可变参数函数(二)
    可变参数函数(一)
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3715518.html
Copyright © 2011-2022 走看看