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...
    土汪閱讀 12,771評論 0 33
  • 以前學習過分形幾何,很有意思,由簡單的數學公式迭代計算得到的分形圖形,放大后不會丟失細節。典型的如Mandelbr...
    rome753閱讀 9,138評論 1 23
  • 首先要先擁有自己的“鵝”。可以將每一筆收入分成金鵝賬戶、夢想基金和日常消費,分配比例根據實際而定。但有兩點需要注意...
    墨瞳_3611閱讀 214評論 0 0