-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerializeDeserializeBinaryTree.java
40 lines (35 loc) · 1.08 KB
/
SerializeDeserializeBinaryTree.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
import java.util.ArrayList;
import java.util.List;
public class SerializeDeserializeBinaryTree {
public String serialize(TreeNode root) {
List<String> res = new ArrayList<>();
dfsSerialize(root, res);
return String.join(",", res);
}
private void dfsSerialize(TreeNode node, List<String> res) {
if (node == null) {
res.add("N");
return;
}
res.add(String.valueOf(node.val));
dfsSerialize(node.left, res);
dfsSerialize(node.right, res);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] vals = data.split(",");
int[] i = {0};
return dfsDeserialize(vals, i);
}
private TreeNode dfsDeserialize(String[] vals, int[] i) {
if (vals[i[0]].equals("N")) {
i[0]++;
return null;
}
TreeNode node = new TreeNode(Integer.parseInt(vals[i[0]]));
i[0]++;
node.left = dfsDeserialize(vals, i);
node.right = dfsDeserialize(vals, i);
return node;
}
}