Skip to content

Commit 56b5ccd

Browse files
authored
Create 297.Serialize-and-Deserialize-Binary-Tree_v3.cpp
1 parent f9e05da commit 56b5ccd

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
13+
// Encodes a tree to a single string.
14+
string serialize(TreeNode* root)
15+
{
16+
if (root==NULL) return "#";
17+
return to_string(root->val)+","+serialize(root->left)+","+serialize(root->right);
18+
}
19+
20+
// Decodes your encoded data to tree.
21+
TreeNode* deserialize(string data)
22+
{
23+
cout<<data<<endl;
24+
queue<string>q;
25+
for (int i=0; i<data.size(); i++)
26+
{
27+
int j=i;
28+
while (j<data.size() && data[j]!=',')
29+
j++;
30+
q.push(data.substr(i,j-i));
31+
i=j;
32+
}
33+
return DFS(q);
34+
}
35+
36+
TreeNode* DFS(queue<string>&q)
37+
{
38+
string cur = q.front();
39+
q.pop();
40+
41+
if (cur=="#") return NULL;
42+
TreeNode* root = new TreeNode(stoi(cur));
43+
44+
TreeNode* left = DFS(q);
45+
TreeNode* right = DFS(q);
46+
root->left = left;
47+
root->right = right;
48+
return root;
49+
}
50+
};
51+
52+
// Your Codec object will be instantiated and called as such:
53+
// Codec codec;
54+
// codec.deserialize(codec.serialize(root));

0 commit comments

Comments
 (0)