-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem107.java
67 lines (57 loc) · 2.02 KB
/
Problem107.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
60
61
62
63
64
65
66
67
import java.util.ArrayList;
import java.util.List;
class Problem107 {
public static void main(String[] args) {
Problem107 p = new Problem107();
TreeNode root = new TreeNode(1);/*
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
root.left.left.left = new TreeNode(8);
root.left.left.right = new TreeNode(9);
root.right.left.left = new TreeNode(10);
root.right.left.right = new TreeNode(11);
root.right.right.right = new TreeNode(12);*/
System.out.println(p.levelOrderBottom(root));
}
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null) {
return new ArrayList<List<Integer>>();
}
List<TreeNode> nodes = new ArrayList<>();
nodes.add(root);
List<List<Integer>> integers = new ArrayList<>();
List<Integer> res1 = traverse(nodes, integers);
if (res1.size() > 0) {
integers.add(res1);
}
//add root
List<Integer> res2 = new ArrayList<>();
res2.add(root.val);
integers.add(res2);
return integers;
}
List<Integer> traverse(List<TreeNode> nodes, List<List<Integer>> res) {
List<TreeNode> subNodes = new ArrayList<>();
List<Integer> integers = new ArrayList<>();
if (nodes.size() <= 0 || nodes == null) {
return integers;
}
for (TreeNode var : nodes) {
if (var.left != null) {
subNodes.add(var.left);
integers.add(var.left.val);
}
if (var.right != null) {
subNodes.add(var.right);
integers.add(var.right.val);
}
}
List<Integer> vals = traverse(subNodes, res);
if (vals.size() > 0) res.add(vals);
return integers;
}
}