-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_297.java
More file actions
45 lines (39 loc) · 1.3 KB
/
Copy pathP_297.java
File metadata and controls
45 lines (39 loc) · 1.3 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
package leetcode.hard;
import utils.DataStructures.TreeNode;
@SuppressWarnings({ "ConstantConditions", "ReturnOfNull", "InnerClassMayBeStatic" })
public class P_297 {
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
final StringBuilder sb = new StringBuilder();
dfs(root, sb);
return sb.toString();
}
private void dfs(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.append("#,");
return;
}
sb.append(node.val + ",");
dfs(node.left, sb);
dfs(node.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
return build(data.split(","), new int[] { 0 });
}
private TreeNode build(String[] arr, int[] idx) {
if (idx[0] == arr.length) {
return null;
}
final String curr = arr[idx[0]++];
if ("#".equals(curr)) {
return null;
}
final TreeNode root = new TreeNode(Integer.parseInt(curr));
root.left = build(arr, idx);
root.right = build(arr, idx);
return root;
}
}
}