2019年11月8日 星期五

Serialize and Deserialize Binary Tree


Serialize and Deserialize Binary Tree

  • Lintcode : 7 / Leetcode : 297
  • Level : Medium

Problem

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'.

Example
Example 1:

Input:{3,9,20,#,#,15,7}
Output:{3,9,20,#,#,15,7}
Explanation:
Binary tree {3,9,20,#,#,15,7},  denote the following structure:
      3
     / \
    9  20
      /  \
     15   7
it will be serialized {3,9,20,#,#,15,7}
Example 2:

Input:{1,2,3}
Output:{1,2,3}
Explanation:
Binary tree {1,2,3},  denote the following structure:
   1
  / \
 2   3
it will be serialized {1,2,3}
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.

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.

Concept & Algorithm

Time Complexity & Space Complexity

time : O(nodes number)
space: O(nodes number)

Answer

/**
 * 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) {
        string ans = "";
        if (root == nullptr) return ans;
        queue<TreeNode*> q;
        q.push(root);
        ans += to_string(root -> val);
        ans += ",";
        while (!q.empty()) {
            TreeNode * n = q.front(); q.pop();
            if (n -> left == nullptr) {
                ans += "#";
            }else {
                ans += to_string(n -> left -> val);
                q.push(n -> left);
            }
            ans += ",";
            if (n -> right == nullptr) {
                ans += "#";
            }else {
                ans += to_string(n -> right -> val);
                q.push(n -> right);
            }
            ans += ",";
        }
        int s = ans.size() - 1;
        while (ans[s] == '#' || ans[s] == ',') s--;
        return ans.substr(0, s + 1) += ",";
    }

    /**
     * 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) {
        if (data.size() == 0) return nullptr;
        int index = data.find(",");
        TreeNode * root = new TreeNode(stoi(data.substr(0, index)));
        TreeNode * dummy = root;
        data = data.substr(index + 1);
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            TreeNode * t = q.front(); q.pop();

            // left node
            index = data.find(",");
            if (index == -1) break;
            string str = data.substr(0, index);
            if (str != "#") {
                t -> left = new TreeNode(stoi(str));
                q.push(t -> left);
            }
            data = data.substr(index + 1);

            // right node
            index = data.find(",");
            if (index == -1) break;
            str = data.substr(0, index);
            if (str != "#") {
                t -> right = new TreeNode(stoi(str));
                q.push(t -> right);
            }
            data = data.substr(index + 1);
        }
        return dummy;
    }
};
tags: BFS

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...