forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialize-and-deserialize-bst.cpp
59 lines (52 loc) · 1.54 KB
/
serialize-and-deserialize-bst.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
// Time: O(n)
// Space: O(h)
/**
* 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) {
string data;
serializeHelper(root, &data);
return data;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int i = 0;
return deserializeHelper(numeric_limits<int>::min(), numeric_limits<int>::max(), data, &i);
}
private:
void serializeHelper(TreeNode *node, string *data) {
if (node) {
*data += to_string(node->val) + " ";
serializeHelper(node->left, data);
serializeHelper(node->right, data);
}
}
TreeNode* deserializeHelper(int minVal, int maxVal, const string& data, int *i) {
if (*i == data.length()) {
return nullptr;
}
int j = data.find(' ', *i);
auto val = stoi(data.substr(*i, j - *i));
if (minVal < val && val < maxVal) {
auto node = new TreeNode(val);
*i = j + 1;
node->left = deserializeHelper(minVal, val, data, i);
node->right = deserializeHelper(val, maxVal, data, i);
return node;
} else {
return nullptr;
}
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));