-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversalII.java
More file actions
74 lines (71 loc) · 2.29 KB
/
BinaryTreeLevelOrderTraversalII.java
File metadata and controls
74 lines (71 loc) · 2.29 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
int count = 1;
int nextCount = 0;
List<List<Integer>> result = new ArrayList<>();
List<Integer> currentLevel = new ArrayList<>();
while(!q.isEmpty() && q.peek() != null) {
TreeNode node = q.poll();
if (node.left != null) {
nextCount++;
q.offer(node.left);
}
if (node.right != null) {
nextCount++;
q.offer(node.right);
}
count--;
currentLevel.add(node.val);
if (count == 0) {
result.add(0, currentLevel);
currentLevel = new ArrayList<>();
count = nextCount;
nextCount = 0;
}
}
return result;
}
}
//Recursion solution, O(N^2)
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
int max = getMaxLevel(root);
for (int i = max - 1; i >= 0; --i) {
ArrayList<Integer> result = new ArrayList<Integer>();
findSameLevel(root, i, result);
results.add(result);
}
return results;
}
public int getMaxLevel(TreeNode root) {
if (root!= null) {
return Math.max(getMaxLevel(root.left), getMaxLevel(root.right)) + 1;
} else {
return 0;
}
}
public void findSameLevel(TreeNode root, int level, ArrayList<Integer> result){
if (root != null) {
if (level > 0) {
findSameLevel(root.left, level - 1, result);
findSameLevel(root.right, level - 1, result);
} else {
result.add(root.val);
}
}
}
}