序列化二叉树

Desicription

请实现两个函数,分别用来序列化和反序列化二叉树

Solution

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
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
private:
vector<int> buffer;
void OnSerialize(TreeNode* root) {
if(!root) {
buffer.push_back(INT_MIN);
return ;
} else {
buffer.push_back(root->val);
OnSerialize(root->left);
OnSerialize(root->right);
}
}
TreeNode* OnDeserialize(int*& index) {
if(*index == INT_MIN) {
index++;
return nullptr;
} else {
auto res = new TreeNode(*index);
index++;
res->left = OnDeserialize(index);
res->right = OnDeserialize(index);
return res;
}
}
public:
char* Serialize(TreeNode* root) {
OnSerialize(root);
auto intBuffer = new int[buffer.size()];
for(int i = 0; i < buffer.size(); i++) {
intBuffer[i] = buffer[i];
}
return (char*) intBuffer;
}
TreeNode* Deserialize(char* str) {
auto intStr = (int*) str;
return OnDeserialize(intStr);
}
};