-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path297.cpp
46 lines (43 loc) · 1.11 KB
/
297.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
// preorder.cpp
/**
* 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 {
TreeNode *de_preorder(vector<string> &arr, int &index) {
if (arr[index] == "#")
return nullptr;
TreeNode *root = new TreeNode(stoi(arr[index]));
root->left = de_preorder(arr, ++index);
root->right = de_preorder(arr, ++index);
return root;
}
public:
// Encodes a tree to a single string.
string serialize(TreeNode *root) {
if (root == NULL)
return "#\n";
return to_string(root->val) + "\n" + serialize(root->left) +
serialize(root->right);
}
// Decodes your encoded data to tree.
TreeNode *deserialize(string data) {
stringstream ss(data);
vector<string> arr;
string str;
while (!ss.eof()) {
ss >> str;
arr.push_back(str);
}
int index = 0;
return de_preorder(arr, index);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));