-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathCodec.java
73 lines (63 loc) · 2.09 KB
/
Codec.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
package leetcode.tree.levelorder;
import leetcode.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return "";
}
StringBuilder res = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node == null) {
res.append("null").append(",");
} else {
res.append(node.val).append(",");
queue.offer(node.left);
queue.offer(node.right);
}
}
}
return res.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if ("".equals(data)) {
return null;
}
String[] nodes = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int index = 1;
while (index < nodes.length) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if ("null".equals(nodes[index])) {
node.left = null;
} else {
TreeNode left = new TreeNode(Integer.parseInt(nodes[index]));
node.left = left;
queue.offer(left);
}
index++;
if ("null".equals(nodes[index])) {
node.right = null;
} else {
TreeNode right = new TreeNode(Integer.parseInt(nodes[index]));
node.right = right;
queue.offer(right);
}
index++;
}
}
return root;
}
}