zoukankan      html  css  js  c++  java
  • [Interview] Serialize and Deserialize a tree

    A very frequent interview question. Suppose you have a tree, how could you serialize it to file and revert it back?


    for example,

                                                   1
                                             /               \
                                            2                 3
                                                 \          /    
                                                 4        5    
                                              /       \
                                             6        7

    [Thoughts]
    一个比较简单直接的做法是,通过前序遍历来做,把所有空节点当做“#”来标示。那么这棵树可以表示为

                                                   1
                                             /               \
                                            2                 3
                                         /       \          /      \
                                      #         4        5       #
                                              /       \
                                             6        7
                                         /      \     /    \
                                        #      #    #     #

    那么前序遍历的结果就是: {'1','2','#','4','6','#','#','7','#','#','3','5','#','#','#'}; 代码如下:


    void Serialize(TreeNode * node, vector<char> &output)
    {
           if(node == NULL)
           {
                 output.push_back('#');
                 return;
           }

           output.push_back(node->val + '0');
           Serialize(node->left, output);
           Serialize(node->right, output);
    }

    而反序列化的代码也就是:

    TreeNode *Deserialize(vector<char> output, int &index)
    {
           if(index > output.size() || output[index] == '#') return NULL;

           TreeNode *node = new TreeNode(output[index] -'0');
           index ++;
           node->left = Deserialize(output, index);
           index++;
           node->right = Deserialize(output, index);
           return node;
    }



    这里只能通过前序遍历来做,中序及后序是行不通的。原因很简单,除了前序以外,其他遍历方式没办法找出头结点。

    除了常规的三种遍历方式意外, 另一种可行的方法就是按层来遍历,同样可行。










  • 相关阅读:
    设计模式(5)>模板方法
    设计模式(2)>工厂方法模式
    分支限界>装载问题
    解决Oracle 11g在用EXP导出时,空表不能导出
    设计模式(7)>观察者模式
    算法>并行算法
    设计模式(15)>桥接模式
    设计模式(9)>迭代器模式
    设计模式(11)>建造者模式
    设计模式(17)>中介者模式
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078882.html
Copyright © 2011-2022 走看看