LintCode 7. Binary Tree Serialization

原题

LintCode 7. Binary Tree Serialization

Description

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

Notice

There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.

Example

An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:

  3
 / \
9  20
  /  \
 15   7

Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

代码

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /**
    * This method will be invoked first, you should design your own algorithm
    * to serialize a binary tree which denote by a root node to a string which
    * can be easily deserialized by your own "deserialize" method later.
    */
    string serialize(TreeNode * root) {
        // write your code here
        string res = "";
        if (root == NULL) return res;
        queue<TreeNode *> q;
        int notNullCount = 1;
        q.push(root);
        while (!q.empty() && notNullCount) {
            TreeNode *node = q.front();
            q.pop();
            if (node == NULL) {
                res += "#,";
                q.push(NULL);
                q.push(NULL);
            } else {
                notNullCount--;
                res += to_string(node->val) + ",";
                q.push(node->left);
                q.push(node->right);
                if (node->left) notNullCount++;
                if (node->right) notNullCount++;
            }
        }
        return res;
    }

    /**
    * This method will be invoked second, the argument data is what exactly
    * you serialized at method "serialize", that means the data is not given by
    * system, it's given by your own serialize method. So the format of data is
    * designed by yourself, and deserialize it here as you serialize it in
    * "serialize" method.
    */
    TreeNode * deserialize(string &data) {
        // write your code here
        vector<string> vals;
        vector<TreeNode *> nodes;
        stringstream ss(data);
        string temp;
        while (getline(ss, temp, ',')) {
            vals.push_back(temp);
        }
        for (string val : vals) {
            if (val == "#") {
                nodes.push_back(NULL);
            } else {
                TreeNode *node = new TreeNode(stoi(val));
                if (!nodes.empty()) {
                    if (nodes.size() % 2) {
                        nodes[(nodes.size() - 1) / 2]->left = node;
                    } else {
                        nodes[(nodes.size() - 1) / 2]->right = node;
                    }
                }
                nodes.push_back(node);
            }
        }
        return nodes.empty() ? NULL : nodes.front();
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,348评论 0 33
  • 以前学习过分形几何,很有意思,由简单的数学公式迭代计算得到的分形图形,放大后不会丢失细节。典型的如Mandelbr...
    rome753阅读 12,988评论 1 23
  • 首先要先拥有自己的“鹅”。可以将每一笔收入分成金鹅账户、梦想基金和日常消费,分配比例根据实际而定。但有两点需要注意...
    墨瞳_3611阅读 1,488评论 0 0