Skip to content

Commit 44e2ece

Browse files
authored
Create serializedeserialize.cpp
1 parent e85a568 commit 44e2ece

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

BST/serializedeserialize.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Codec {
2+
public:
3+
// Encodes a tree to a single string.
4+
string serialize(TreeNode* root) {
5+
if(!root) return "x,";
6+
string l=serialize(root->left);
7+
string r=serialize(root->right);
8+
return to_string(root->val)+","+l+r;
9+
}
10+
11+
TreeNode* deserializeHelper(queue<string>& q) {
12+
string ch=q.front();
13+
q.pop();
14+
if(ch=="x") return NULL;
15+
TreeNode* root=new TreeNode(stoi(ch));
16+
root->left=deserializeHelper(q);
17+
root->right=deserializeHelper(q);
18+
return root;
19+
}
20+
21+
// Decodes your encoded data to tree.
22+
TreeNode* deserialize(string data) {
23+
stringstream ss(data);
24+
queue<string> q;
25+
cout << data<< endl;
26+
while (ss.good()) {
27+
string str;
28+
getline(ss, str,',');
29+
q.push(str);
30+
}
31+
return deserializeHelper(q);
32+
}
33+
};

0 commit comments

Comments
 (0)