-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCodec.java
More file actions
38 lines (32 loc) · 1002 Bytes
/
Copy pathCodec.java
File metadata and controls
38 lines (32 loc) · 1002 Bytes
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
import java.util.*;
public class Codec
{
private static final String STUB = "#";
private static final String DELIMITER = ",";
public String serialize(TreeNode root)
{
StringBuilder sb = new StringBuilder();
sb.append(root == null ? STUB : root.val).append(DELIMITER);
sb.append(root == null ? "" : serialize(root.left));
sb.append(root == null ? "" : serialize(root.right));
return sb.toString();
}
public TreeNode deserialize(String data)
{
Queue<String> queue = new LinkedList<>();
queue.addAll(Arrays.asList(data.split(DELIMITER)));
return buildTree(queue);
}
private TreeNode buildTree(Queue<String> queue)
{
String node = queue.poll();
if (node.equals(STUB))
{
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(node));
root.left = buildTree(queue);
root.right = buildTree(queue);
return root;
}
}