-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeLevelOrderTraversalII.java
36 lines (31 loc) · 1.13 KB
/
BinaryTreeLevelOrderTraversalII.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
import java.util.ArrayList;
// It might be better to traverse from top level to bottom level and then reverse the results
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
int treeHeight = height(root);
for (int i = treeHeight - 1; i >= 0; i--) {
ArrayList<Integer> values = new ArrayList<Integer>();
traverseLevel(root, i, values);
results.add(values);
}
return results;
}
private int height(TreeNode node) {
if (node == null)
return 0;
int lheight = height(node.left);
int rheight = height(node.right);
return lheight > rheight ? lheight + 1 : rheight + 1;
}
private void traverseLevel(TreeNode node, int level, ArrayList<Integer> values) {
if (node == null)
return;
if (level == 0)
values.add(node.val);
else {
traverseLevel(node.left, level - 1, values);
traverseLevel(node.right, level - 1, values);
}
}
}