请实现两个函数,分别用来序列化和反序列化二叉树
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
|
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public
class
Solution {
public
int
index = -
1
;
String Serialize(TreeNode root) {
StringBuffer sb =
new
StringBuffer();
if
(root ==
null
){
sb.append(
"#,"
);
return
sb.toString();
}
sb.append(root.val +
","
);
sb.append(Serialize(root.left));
sb.append(Serialize(root.right));
return
sb.toString();
}
TreeNode Deserialize(String str) {
index++;
int
len = str.length();
if
(index >= len){
return
null
;
}
String[] strr = str.split(
","
);
TreeNode node =
null
;
if
(!strr[index].equals(
"#"
)){
node =
new
TreeNode(Integer.valueOf(strr[index]));
node.left = Deserialize(str);
node.right = Deserialize(str);
}
return
node;
}
}
|