-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathbinary-tree-serialization(AC).cpp
More file actions
81 lines (73 loc) · 1.71 KB
/
binary-tree-serialization(AC).cpp
File metadata and controls
81 lines (73 loc) · 1.71 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
#include <vector>
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
string serialize(TreeNode *root) {
serializePreorder(root);
string ans = "";
int n = v.size();
int i;
for (i = 0; i < n; ++i) {
ans += v[i];
ans.push_back(' ');
}
ans.pop_back();
v.clear();
return ans;
}
TreeNode *deserialize(string data) {
int n = data.length();
int i, j;
string s;
while (i < n) {
s = "";
j = i;
while (j < n && data[j] != ' ') {
s.push_back(data[j++]);
}
v.push_back(s);
++j;
i = j;
}
idx = 0;
TreeNode *root;
deserializePreorder(root);
v.clear();
return root;
}
private:
vector<string> v;
int idx;
void serializePreorder(TreeNode *root) {
if (root == NULL) {
v.push_back("#");
return;
}
v.push_back(to_string(root->val));
serializePreorder(root->left);
serializePreorder(root->right);
}
void deserializePreorder(TreeNode *&root) {
if (v[idx] == "#") {
root = NULL;
++idx;
} else {
root = new TreeNode(atoi(v[idx].data()));
++idx;
deserializePreorder(root->left);
deserializePreorder(root->right);
}
}
};