剑指Offer_61

题目

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

解题思路

序列化二叉树:

前序遍历二叉树

反序列化二叉树:

根据“#” 的值判断是否应该构造节点

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
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
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();
}
private int index;
private TreeNode DeserializeHelper(String []strings){
++index;
TreeNode node = null;
if(!strings[index].equals("#")){
node = new TreeNode(Integer.valueOf(strings[index]));
node.left = DeserializeHelper(strings);
node.right = DeserializeHelper(strings);
}
return node;
}
TreeNode Deserialize(String str) {
index = -1;
String []strings = str.split(",");
return DeserializeHelper(strings);
}
}