107. Binary Tree Level Order Traversal II
We can reverse the result of top-down level order traversal to solve this problem.
Recursive
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
helper(root, 0, res);
Collections.reverse(res);
return res;
}
private void helper(TreeNode root, int height, List<List<Integer>> res) {
if (root == null) {
return;
}
if (res.size() <= height) {
res.add(new ArrayList<>());
}
res.get(height).add(root.val);
helper(root.left, height + 1, res);
helper(root.right, height + 1, res);
}
}
Iterative
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
int height = 0;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.addLast(root);
while (!queue.isEmpty()) {
// create a list for the current level
res.add(new ArrayList<>());
// add all elements in the current level to the list
int elementLen = queue.size();
for (int i = 0; i < elementLen; i++) {
TreeNode node = queue.removeFirst();
res.get(height).add(node.val);
if (node.left != null) {
queue.addLast(node.left);
}
if (node.right != null) {
queue.addLast(node.right);
}
}
// go to the next level
height++;
}
Collections.reverse(res);
return res;
}
}