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;
    }



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

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










  • 相关阅读:
    排队打饭 sdut 2443【最简单的贪心法应用举例】
    sdut 2445 小学数学
    最终排名 sdut 2446
    sort函数用法
    sdut1598 周游列国【简单模拟题】
    sdut 2441 屠夫与狼
    男生女生分配
    qsort函数详解
    test1.A[【dfs简单题】
    sdut 2449走迷宫【最简单的dfs应用】
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078882.html
Copyright © 2011-2022 走看看