forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path297.Serialize and Deserialize Binary Tree.cpp
69 lines (65 loc) · 1.6 KB
/
297.Serialize and Deserialize Binary Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* 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)
{
queue<TreeNode*>q;
q.push(root);
string ret;
while (!q.empty())
{
TreeNode* node = q.front();
q.pop();
if (node!=NULL)
{
ret+=to_string(node->val)+",";
q.push(node->left);
q.push(node->right);
}
else
ret+="#,";
}
return ret;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data)
{
vector<TreeNode*>nodes;
for (int i=0; i<data.size(); i++)
{
int j = i;
while (j<data.size() && data[j]!=',')
j++;
string str = data.substr(i,j-i);
if (str=="#")
nodes.push_back(NULL);
else
nodes.push_back(new TreeNode(stoi(str)));
i = j;
}
int i = 0, j = 1;
while (j<nodes.size())
{
if (nodes[i]!=NULL)
{
nodes[i]->left = nodes[j];
nodes[i]->right = nodes[j+1];
j+=2;
}
i++;
}
return nodes[0];
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));