-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBTSerializer.java
More file actions
115 lines (96 loc) · 3.33 KB
/
BTSerializer.java
File metadata and controls
115 lines (96 loc) · 3.33 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import java.util.LinkedList;
import java.util.Queue;
public class BTSerializer {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return new String();
}
String serialized = new String();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
serialized += "[";
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
serialized += "null";
} else {
serialized += Integer.toString(node.val);
queue.add(node.left);
queue.add(node.right);
}
if (!queue.isEmpty()) {
serialized += ",";
}
}
serialized += "]";
System.out.println(serialized);
return serialized;
}
private TreeNode deserializeQueue(String data) {
TreeNode root = null;
Queue<TreeNode> toSerialize = new LinkedList<>();
toSerialize.add(root);
while(!toSerialize.isEmpty()) {
TreeNode node = toSerialize.poll();
String tmp = new String();
boolean numberAdj = false;
int count = 0;
for (int i = 0; i < data.length(); i++) {
Character ch = data.charAt(i);
if (ch == '-' || Character.isDigit(ch)) {
tmp += Character.toString(ch);
numberAdj = true;
} else if (ch == ',') {
if (numberAdj) {
int num = Integer.parseInt(tmp);
if (node == null) {
node = new TreeNode(num);
if (root == null) {
root = node;
}
toSerialize.add(node);
data = data.substring(i + 1);
break;
} else if (count == 0) {
node.left = new TreeNode(num);
toSerialize.add(node.left);
numberAdj = false;
tmp = new String();
} else if (count == 1) {
node.right = new TreeNode(num);
toSerialize.add(node.right);
data = data.substring(i + 1);
break;
}
} else {
if (count == 1) {
data = data.substring(i + 1);
break;
}
}
count++;
} else if (ch == ']') {
toSerialize.clear();
break;
}
}
}
return root;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.length() <= 3) {
return null;
}
data = data.substring(1); // removing '['
TreeNode root = deserializeQueue(data);
return root;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}