Offer.P37[序列化二叉树]

方法一:BFS

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {

private static final String EMPTY = "null";

// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return "";
StringBuilder builder = new StringBuilder();
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur == null) {
builder.append(EMPTY).append(",");
} else {
builder.append(cur.val).append(",");
queue.offer(cur.left);
queue.offer(cur.right);
}
}
return builder.toString();
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.equals("")) return null;
String[] split = data.split(",");
Deque<String> nodes = new LinkedList<>(List.of(split));
TreeNode root = new TreeNode(Integer.parseInt(nodes.poll()));
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
String left = nodes.poll();
String right = nodes.poll();
if (!left.equals(EMPTY)) {
cur.left = new TreeNode(Integer.parseInt(left));
queue.offer(cur.left);
}
if (!right.equals(EMPTY)) {
cur.right = new TreeNode(Integer.parseInt(right));
queue.offer(cur.right);
}
}
return root;
}
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

方法二:DFS

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {

private static final String EMPTY = "null";

// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return EMPTY + ",";
String left = serialize(root.left);
String right = serialize(root.right);
return root.val + "," + left + right;
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] nodes = data.split(",");
Deque<String> queue = new LinkedList<>(List.of(nodes));
return buildTree(queue);
}

public TreeNode buildTree(Deque<String> queue) {
String cur = queue.poll();
if (cur.equals(EMPTY)) return null;
TreeNode node = new TreeNode(Integer.parseInt(cur));
node.left = buildTree(queue);
node.right = buildTree(queue);
return node;
}
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));