297. Serialize and Deserialize Binary Tree
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 uses BFS traversal. This is just for when you got a Wrong Answer and want to debug the input.
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
- class Codec {
- public:
- // Encodes a tree to a single string.
- string serialize(TreeNode* root) {
- if (root == NULL) return "";
- queue<TreeNode*> q;
- q.push(root);
- string result = "";
- while (!q.empty()) {
- TreeNode *curr = q.front();
- q.pop();
- if (!result.empty()) result += ",";
- if (curr == NULL) {
- result += "#";
- continue;
- }
- result += to_string(curr->val);
- q.push(curr->left);
- q.push(curr->right);
- }
- return result;
- }
- // Decodes your encoded data to tree.
- TreeNode* deserialize(string data) {
- if (data.empty()) return NULL;
- vector<string> ds = split(data, ",");
- TreeNode *root = new TreeNode(stoi(ds[0]));
- queue<TreeNode*> q;
- q.push(root);
- bool isRight = false;
- for (int i = 1; i < ds.size(); i++) {
- if (ds[i] != "#") {
- TreeNode *node = new TreeNode(stoi(ds[i]));
- if (isRight) {
- q.front()->right = node;
- } else {
- q.front()->left = node;
- }
- q.push(node);
- }
- if (isRight) q.pop();
- isRight = !isRight;
- }
- return root;
- }
- vector<string> split(const string &data, string separator) {
- vector<string> result;
- int index, lastIndex = 0;
- while ((index = data.find(separator, lastIndex)) != string::npos) {
- result.push_back(data.substr(lastIndex, index - lastIndex));
- lastIndex = index + separator.length();
- }
- if (lastIndex != data.length()) result.push_back(data.substr(lastIndex));
- return result;
- }
- };
C++ does not have a split function.

Comments
Post a Comment