-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializeDeserializeBinaryTree.cpp
More file actions
109 lines (89 loc) · 2.81 KB
/
SerializeDeserializeBinaryTree.cpp
File metadata and controls
109 lines (89 loc) · 2.81 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* 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) {
if(!root) return "";
string result="";
queue<TreeNode*> mytree;
mytree.push(root);
TreeNode* temp;
while(!mytree.empty()){
temp = mytree.front();
mytree.pop();
if(temp != NULL){
result += to_string(temp->val) + ",";
}
else{
result += "n,";
}
if(temp){
mytree.push(temp->left);
mytree.push(temp->right);
}
}
//result.pop_back();
int startIndex =result.length();
for(int i = result.length()-1; i>=0; i = i-2){
if(result[i] == ',' && result[i-1] == 'n')
{
startIndex = i-1;
}
else{
break;
}
}
result = result.substr(0,startIndex);
return result;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty()) return NULL;
TreeNode * root;
TreeNode* temp;
vector<string> nodes;
while(!data.empty()){
auto first = data.find_first_of(",");
nodes.push_back(data.substr(0,first-0));
data.erase(0,first+1);
}
int cnt =0;
int val = stoi(nodes[cnt++]);
int LEN = nodes.size();
// nodes.erase(nodes.begin());
queue<TreeNode*> stk;
root = new TreeNode(val);
stk.push(root);
TreeNode * Node;
while(cnt < LEN){
Node = stk.front();
stk.pop();
if(cnt < LEN){
Node->left = nodes[cnt] == "n"?nullptr:new TreeNode(stoi(nodes[cnt]));
cnt++;
//nodes.erase(nodes.begin());
}
if(cnt < LEN){
Node->right = nodes[cnt] == "n"? nullptr: new TreeNode(stoi(nodes[cnt]));
cnt++;
//nodes.erase(nodes.begin());
}
if(Node->left)
stk.push(Node->left);
if(Node->right)
stk.push(Node->right);
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));