-
Notifications
You must be signed in to change notification settings - Fork 17
/
Que61.java
70 lines (49 loc) · 1.34 KB
/
Que61.java
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
/**
* @author: hyl
* @date: 2019/08/18
**/
public class Que61 {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
//使用前序序列化
String Serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
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 = -1;
TreeNode Deserialize(String str) {
index++;
int len = str.length();
String[] nodeStr = str.split(",");
TreeNode node = null;
if (index >= len){
return null;
}
if (!nodeStr[index].equals("#")){
node = new TreeNode(Integer.valueOf(nodeStr[index]));
node.left = Deserialize(str);
node.right = Deserialize(str);
}
return node;
}
public static void main(String[] args) {
TreeNode node = new TreeNode(1);
node.left = new TreeNode(5);
node.right = new TreeNode(6);
new Que61().Serialize(node);
}
}