【剑指Offer】序列化二叉树

题目

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

实现

1
2
3
4
5
6
7
8
9
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
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
private int idx = -1;

public String Serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();

if (root == null) {
sb.append("$,");
return sb.toString();
}

sb.append(root.val).append(",");
sb.append(Serialize(root.left));
sb.append(Serialize(root.right));

return sb.toString();
}

public TreeNode Deserialize(String str) {
if (str == null || str.length() < 1)
return null;

String[] strs = str.split(",");

return Deserialize(strs);
}

private TreeNode Deserialize(String[] strs) {
idx++;
TreeNode root = null;

if (idx < strs.length && !strs[idx].equals("$")) {
root = new TreeNode(Integer.valueOf(strs[idx]));
root.left = Deserialize(strs);
root.right = Deserialize(strs);
}

return root;
}