Skip to content

Commit daa3053

Browse files
committed
Serialize and Deserialize Binay Tree solution
1 parent 31ccab7 commit daa3053

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
class Codec {
2+
public:
3+
// Encodes a tree to a single string.
4+
string serialize(TreeNode* root) {
5+
string result;
6+
7+
if(root == nullptr)
8+
return result;
9+
10+
queue<TreeNode*> q;
11+
12+
q.push(root);
13+
14+
while(!q.empty()){
15+
TreeNode* curr = q.front();
16+
17+
q.pop();
18+
19+
if(curr){
20+
result += to_string(curr->val) + ",";
21+
q.push(curr->left);
22+
q.push(curr->right);
23+
}else{
24+
result += "NULL,";
25+
}
26+
}
27+
28+
return result;
29+
}
30+
// Decodes your encoded data to tree.
31+
TreeNode* deserialize(string data) {
32+
if(!data.size())
33+
return nullptr;
34+
35+
queue<TreeNode*> q;
36+
vector<string> values;
37+
size_t prev = 0;
38+
size_t pos = data.find(",", prev);
39+
40+
while(pos != string::npos){
41+
values.push_back(data.substr(prev, pos - prev));
42+
prev = pos + 1;
43+
pos = data.find(",", prev);
44+
}
45+
46+
int idx = 0;
47+
TreeNode* root = new TreeNode(stoi(values[idx++]));
48+
q.push(root);
49+
50+
while(!q.empty()){
51+
int left = idx++;
52+
int right = idx++;
53+
TreeNode* curr = q.front();
54+
q.pop();
55+
56+
if(left < values.size() && values[left] != "NULL"){
57+
curr->left = new TreeNode(stoi(values[left]));
58+
q.push(curr->left);
59+
}
60+
61+
if(right < values.size() && values[right] != "NULL"){
62+
curr->right = new TreeNode(stoi(values[right]));
63+
q.push(curr->right);
64+
}
65+
}
66+
67+
return root;
68+
}
69+
};

0 commit comments

Comments
 (0)