-
Notifications
You must be signed in to change notification settings - Fork 0
/
449 SerializeandDeserializeBST.cpp
77 lines (61 loc) · 1.59 KB
/
449 SerializeandDeserializeBST.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
/**
* 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) {
tree.clear();
preorder(root);
ostringstream oss;
if (!tree.empty())
{
copy(tree.begin(), tree.end() - 1, ostream_iterator<int>(oss, ","));
oss << tree.back();
}
return oss.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
tree.clear();
istringstream iss(data);
string token;
while(getline(iss, token, ','))
tree.push_back(stoi(token));
int i = 0;
return makeTree(i);
}
private:
vector<int> tree;
void preorder(TreeNode* node) {
if(node) {
tree.push_back(node->val);
preorder(node->left);
preorder(node->right);
}
else
tree.push_back(-1);
}
TreeNode* makeTree(int& i) {
if(tree[i] == -1) {
++i;
return nullptr;
}
TreeNode* node = new TreeNode(tree[i++]);
node->left = makeTree(i);
node->right = makeTree(i);
return node;
}
};
// 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;