-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeNode.java
More file actions
54 lines (46 loc) · 1.44 KB
/
Copy pathTreeNode.java
File metadata and controls
54 lines (46 loc) · 1.44 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
package com.al.tree;
import java.util.ArrayList;
import java.util.Arrays;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
val = x;
}
static StringBuilder serialhelper(TreeNode root, StringBuilder builder) {
if (root == null) {
return builder.append("#,");
}
builder.append(root.val).append(',');
builder = serialhelper(root.left, builder);
builder = serialhelper(root.right, builder);
return builder;
}
// Encodes a tree to a single string.
static String serialize(TreeNode root) {
StringBuilder builder = new StringBuilder();
serialhelper(root, builder);
return builder.toString();
}
static TreeNode deserialhelper(ArrayList<String> al) {
if (al.get(0).equals("#")) {
al.remove(0);
return null;
}
TreeNode tn = new TreeNode(Integer.valueOf(al.remove(0).toString()));
tn.left = deserialhelper(al);
tn.right = deserialhelper(al);
return tn;
}
// Decodes your encoded data to tree.
public static TreeNode deserialize(String data) {
return deserialhelper(new ArrayList<>(Arrays.asList(data.split(","))));
}
public static void preOrder(TreeNode t){
if (t == null) return;
System.out.println(t.val);
preOrder(t.left);
preOrder(t.right);
}
}