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



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

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










  • 相关阅读:
    zedGraph画心电图
    多窗体之间进行数据通信 传值
    C#共有五种访问修饰符:public、private、protected、internal、protected internal。作用范围如下表:
    Linux进程调度与切换
    Linux学习总结
    Linux内核如何启动并装载一个可执行程序
    Linux编写Shell脚本入门
    如何使用委托
    深入剖析反射
    浅析C#中的文件操作
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078882.html
Copyright © 2020-2023  润新知