LeetCode 449. 序列化和反序列化二叉搜索树

思路

BFS,广度优先遍历,通一5位数存储和读取。
由于val是小于等于1e4,五位字符串可以存储。

sprintf(str,”%05d”,num);

将数字通一转化为5位长的字符串。

stoi(data.substr(p,5));

把5位长的字符串转化为数字。
一层一层,从左到右遍历,存储遍历结果,读取构造搜索二叉树也是从左到右即可。

代码

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
/**
* 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:
void InOrder(string &res,TreeNode* root){
if(root==nullptr) return;
queue<TreeNode*> q;
char data[6];
q.push(root);
while(!q.empty()){
TreeNode* t=q.front();
q.pop();
if(t->left!=nullptr) q.push(t->left);
if(t->right!=nullptr) q.push(t->right);
sprintf(data,"%05d",t->val);
res+=data;
}
}
void SetNum(TreeNode* root,int key){
if(root->val > key){
if(root->left!=nullptr)
SetNum(root->left,key);
else
root->left=new TreeNode(key);
}
else if(root->val < key){
if(root->right!=nullptr)
SetNum(root->right,key);
else
root->right=new TreeNode(key);
}
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res="";
InOrder(res,root);
cout<<res<<endl;
return res;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode* res=nullptr;
TreeNode* temp;
int p=0;
while(p+4<data.length()){
int num=stoi(data.substr(p,5));
cout<<num<<endl;
if(res==nullptr){
res=new TreeNode(num);
}else{
SetNum(res,num);
}
p+=5;
}
return res;
}
};

// 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;

参考