-
Notifications
You must be signed in to change notification settings - Fork 110
/
297-serialize-and-deserialize-binary-tree.cpp
78 lines (74 loc) · 1.98 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
70
71
72
73
74
75
76
77
78
/**
* 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:
void preOrder(TreeNode* root, string& s) {
if (!root) {
s += "x,";
return;
}
s += to_string(root->val);
s += ',';
preOrder(root->left, s);
preOrder(root->right, s);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) return "";
string toReturn = "";
preOrder(root, toReturn);
return toReturn;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int n = data.size();
if (n == 0) return NULL;
vector<int> dVec;
int i = 0;
int j = 0;
while (i < n) {
if (data[j] == 'x') {
dVec.push_back(INT_MIN);
j += 2;
i = j;
continue;
}
if (data[j] == ',') {
dVec.push_back(stoi(data.substr(i, j - i)));
i = ++j;
} else {
j++;
}
}
stack<pair<TreeNode*, int>> s;
TreeNode* root = new TreeNode(dVec[0]);
s.emplace(root, 0);
for (int i = 1; i < dVec.size(); i++) {
TreeNode* p = nullptr;
if (dVec[i] != INT_MIN) {
p = new TreeNode(dVec[i]);
}
if (s.top().second == 0) {
s.top().first->left = p;
s.top().second = 1;
} else if (s.top().second == 1) {
s.top().first->right = p;
s.pop();
}
if (p) {
s.emplace(p, 0);
}
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));