...

/

Reverse Level Order Traversal (easy)

Reverse Level Order Traversal (easy)

Problem Statement

Given a binary tree, populate an array to represent its level-by-level traversal in reverse order, i.e., the lowest level comes first. You should populate the values of all nodes in each level from left to right in separate sub-arrays.

Example 1:

Example 2:

Try it yourself

Try solving this question here:

import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
};
class ReverseLevelOrderTraversal {
public static List<List<Integer>> traverse(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
// TODO: Write your code here
return result;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(12);
root.left = new TreeNode(7);
root.right = new TreeNode(1);
root.left.left = new TreeNode(9);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(5);
List<List<Integer>> result = ReverseLevelOrderTraversal.traverse(root);
System.out.println("Reverse level order traversal: " + result);
}
}

Solution

This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only difference will be that instead of appending the current level at the end, we will append the current level at the beginning of the result list.

Code

Here is what our algorithm will look like; only the highlighted lines have changed. Please note that, for ...