-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy path449_Serialize_and_Deserialize_BST.java
44 lines (35 loc) · 1.17 KB
/
449_Serialize_and_Deserialize_BST.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
public class Codec {
private String DELIMETER = ",";
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
preorder(root, sb);
return sb.toString();
}
private void preorder(TreeNode root, StringBuilder sb) {
if (root == null) {
return;
}
sb.append(root.val).append(DELIMETER);
preorder(root.left, sb);
preorder(root.right, sb);
}
public TreeNode deserialize(String data) {
if (data == null || data.length() == 0) {
return null;
}
Queue<String> q = new LinkedList<>(Arrays.asList(data.split(DELIMETER)));
return deserialize(q, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private TreeNode deserialize(Queue<String> q, int min, int max) {
if (q.isEmpty())
return null;
if (Integer.valueOf(q.peek()) < min || Integer.valueOf(q.peek()) > max) {
return null;
}
int rootVal = Integer.valueOf(q.poll());
TreeNode t = new TreeNode(rootVal);
t.left = deserialize(q, min, rootVal);
t.right = deserialize(q, rootVal, max);
return t;
}
}