-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode0297.java
59 lines (50 loc) · 1.63 KB
/
LeetCode0297.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* Serialize and Deserialize Binary Tree
* Input:
* 1
/ \
2 3
/ \
4 5
* Output: Same as input
* */
public class LeetCode0297 {
public static int index = 0;
public static int[] TREE_VALUE = new int[]{1, 2, 0, 0, 3, 4, 0, 0, 5, 0, 0};
public static void main(String args[]) {
TreeNode root = new TreeNode();
root = TreeNode.createTree(root, index, TREE_VALUE);
System.out.println(serialize(root));
TreeNode.output(deserialize(serialize(root)));
}
// Encodes a tree to a single string.
static String str = new String();
public static String serialize(TreeNode root) {
if (root == null)
str += "null" + ",";
else {
str += str.valueOf(root.val) + ",";
serialize(root.left);
serialize(root.right);
}
return str;
}
// Decodes your encoded data to tree.
static int index1 = 0;
public static TreeNode deserialize(String data) {
TreeNode root = new TreeNode();
String[] s = data.split(",");
return repreorder(root, index1, s);
}
public static TreeNode repreorder(TreeNode node, int i, String[] s) {
if (s[i].equals("null")) {
return null;
} else {
node.val = Integer.valueOf(s[i]);
}
TreeNode leftChild = new TreeNode();
node.left = repreorder(leftChild, ++index1, s);
TreeNode rightChild = new TreeNode();
node.right = repreorder(rightChild, ++index1, s);
return node;
}
}