-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSerializeBinaryTree.java
83 lines (58 loc) · 1.75 KB
/
SerializeBinaryTree.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
71
72
73
74
75
76
77
78
79
80
81
82
83
package org.offer.case62;
import org.offer.utils.node.BinaryTreeNode;
/**
* 面试题 62: 序列化二叉树
* Created by tanc on 2017/7/12.
*/
public class SerializeBinaryTree {
/**
* 序列化
* 使用前序遍历,空节点使用特殊字符占位。
*/
public static <E> String serialize(BinaryTreeNode<E> root) {
if (null == root) {
return null;
}
StringBuilder builder = new StringBuilder();
serialize(root, builder);
builder.deleteCharAt(builder.lastIndexOf(","));
return builder.toString();
}
private static <E> void serialize(BinaryTreeNode<E> root, StringBuilder builder) {
if (null == root) {
builder.append("$,");
return;
}
builder.append(root.data).append(",");
serialize(root.left, builder);
serialize(root.right, builder);
}
/**
* 反序列化
*/
public static BinaryTreeNode<Integer> deserialize(String string) throws Exception {
if (null == string) {
return null;
}
index = 0;
String[] arr = string.split(",");
BinaryTreeNode<Integer> result = deserialize(arr);
index = 0;
return result;
}
private static int index = 0;
private static BinaryTreeNode<Integer> deserialize(String[] arr) {
if (index >= arr.length) {
return null;
}
String data = arr[index++];
if (data.equals("$")) {
return null;
}
Integer dataInt = Integer.parseInt(data);
BinaryTreeNode<Integer> node = new BinaryTreeNode<>(dataInt);
node.left = deserialize(arr);
node.right = deserialize(arr);
return node;
}
}