-
Notifications
You must be signed in to change notification settings - Fork 0
/
297. Serialize and Deserialize Binary Tree
57 lines (46 loc) · 1.72 KB
/
297. Serialize and Deserialize Binary Tree
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
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return "[]";
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
sb.append("null,");
} else {
sb.append(node.val).append(",");
queue.add(node.left);
queue.add(node.right);
}
}
sb.deleteCharAt(sb.length() - 1); // Remove the trailing comma
return "[" + sb.toString() + "]";
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.equals("[]")) return null;
String[] nodes = data.substring(1, data.length() - 1).split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < nodes.length) {
TreeNode parent = queue.poll();
if (!nodes[i].equals("null")) {
TreeNode left = new TreeNode(Integer.parseInt(nodes[i]));
parent.left = left;
queue.add(left);
}
i++;
if (i < nodes.length && !nodes[i].equals("null")) {
TreeNode right = new TreeNode(Integer.parseInt(nodes[i]));
parent.right = right;
queue.add(right);
}
i++;
}
return root;
}
}