-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsolution.cpp
64 lines (58 loc) · 1.61 KB
/
solution.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* 62 / 62 test cases passed.
* Runtime: 32 ms
* Memory Usage: 26.9 MB
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string ret = "";
preOrder(ret, root);
return ret;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
stringstream ss(data);
queue<string> que;
string s;
while (ss >> s) que.emplace(static_cast<string>(s));
return construct(que, INT_MIN, INT_MAX);
}
private:
void preOrder(string &str, TreeNode *root) {
if (root) {
str += to_string(root->val);
str += " ";
preOrder(str, root->left);
preOrder(str, root->right);
}
}
TreeNode *construct(queue<string> &data, int lower, int upper) {
if (data.empty()) return nullptr;
int val = atoi(data.front().c_str());
if (lower <= val && val <= upper) {
data.pop();
TreeNode *node = new TreeNode(val);
node->left = construct(data, lower, val);
node->right = construct(data, val, upper);
return node;
}
return nullptr;
}
};
// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;