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
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string s;
toS(root,s);
return s;
}
#define Node TreeNode
void toS(Node*p,string &s) {
if(p==NULL) {
s += "n,";
return;
}
s+= to_string(p->val)+",";
toS(p->left,s);
toS(p->right,s);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
// cout << data<<endl;
//return NULL;
int f=0;
return toNode(data,f);
}
Node* toNode(string &p,int &i) {
if(i >= (int)p.size()) return NULL;
if(p[i]==',')++i;
int t = i;
while(p[t]!=',') t++;
if(p[i]=='n') {
i = t+1;
//null 值
return NULL;
}
int val = 0,flag = 1;
if(p[i]==',')++i;
if(p[i]=='-') ++i,flag = -1;
for(int k=i;k<t;++k) {
val = val*10 + (p[k]-'0');
}
val = val*flag;
Node*cur = new Node(val);
i = t+1;
cur->left = toNode(p,i);
cur->right=toNode(p,i);
return cur;
}
};
|