Skip to main content

Binary Tree Level Order Traversal II


Binary Tree Level Order Traversal II: Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).

Example 1:

image

Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]

Example 2:
Input: root = [1]
Output: [[1]]

Example 3:
Input: root = []
Output: []

Constraints:
  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Try this Problem on your own or check similar problems:

  1. Binary Tree Level Order Traversal
  2. Average of Levels in Binary Tree
Solution:
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root == null) return List.of();

Queue<TreeNode> q = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();

q.add(root);

while(!q.isEmpty()){
int size = q.size();
List<Integer> level = new ArrayList<>();
while(size-->0){
TreeNode node = q.poll();
if(node.left != null){
q.add(node.left);
}
if(node.right != null){
q.add(node.right);
}
level.add(node.val);
}
result.add(level);
}

Collections.reverse(result);
return result;
}

Time/Space Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Explanation:

We utilize the same approach we did in Average of Levels in Binary Tree by traversing the tree level by level, and at the end we reverse the level traversal so we start from the last level. If you would be asked to do it without reversing the list, you could calculate the maxHeight of tree which would our first list in the final result and then utilize the same approach but this time just writing to the end of array starting from the maxHeight level.