Skip to content

Commit 848ff1a

Browse files
Added solution
1 parent 7713faa commit 848ff1a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

serialise_deserialise_bst.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Codec {
11+
public:
12+
string serialize(TreeNode* root) {
13+
ostringstream out;
14+
serializeHelper(root, out);
15+
return out.str();
16+
}
17+
18+
// Decodes your encoded data to tree.
19+
TreeNode* deserialize(string data) {
20+
if(data.empty()) {
21+
return NULL;
22+
}
23+
istringstream in(data);
24+
queue<int> q;
25+
string val;
26+
while(in >> val) {
27+
q.push(stoi(val));
28+
}
29+
return deserializeHelper(q, INT_MIN, INT_MAX);
30+
}
31+
private:
32+
void serializeHelper(TreeNode* root, ostringstream& out) {
33+
if(root == NULL)
34+
return;
35+
out << root -> val << " ";
36+
serializeHelper(root->left, out);
37+
serializeHelper(root->right, out);
38+
}
39+
TreeNode* deserializeHelper(queue<int>& q, int lower, int upper) {
40+
if(q.empty())
41+
return NULL;
42+
int cur = q.front();
43+
if(cur < lower || cur > upper) {
44+
return NULL;
45+
}
46+
TreeNode* root = new TreeNode(cur);
47+
q.pop();
48+
root -> left = deserializeHelper(q, lower, cur);
49+
root -> right = deserializeHelper(q, cur, upper);
50+
return root;
51+
}
52+
};
53+
54+
// Your Codec object will be instantiated and called as such:
55+
// Codec codec;
56+
// codec.deserialize(codec.serialize(root));

0 commit comments

Comments
 (0)