Given a binary tree, print its nodes level by level in reverse order, i.e., print all nodes present at the last level first, followed by nodes of the second last level, and so on… Print nodes at any level from left to right.

For example, the reverse level order traversal for the following tree is 4, 5, 6, 7, 2, 3, 1:

 
Level Order Traversal

Practice this problem

A simple solution would be to print all nodes of level h first, followed by level h-1, until level 1, where h is the tree’s height. We can print all nodes present in a level by modifying the preorder traversal on the tree. The time complexity of this solution is O(n2), where n is the total number of nodes in the binary tree.

 
We can reduce the time complexity to O(n) by using extra space. Following is a pseudocode for a simple queue-based reverse level order traversal, which requires space proportional to the maximum number of nodes at a given depth. It can be as much as half of the total number of nodes.

levelorder(root)
 
q —> empty queue
s —> empty stack
q.enqueue(root)
while (not q.isEmpty())
  node —> q.dequeue()
  s.push(node)
  if (node.right <> null)
    q.enqueue(node.right)
  if (node.left <> null)
    q.enqueue(node.left)
 
while (not s.isEmpty())
  node —> s.pop()
  print(node)

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

8 12 16 25 10 20 15

Java


Download  Run Code

Output:

8 12 16 25 10 20 15

Python


Download  Run Code

Output:

8 12 16 25 10 20 15

We can also solve this problem by using hashing. The idea is to traverse the tree in a preorder fashion and store every node and its level in a multimap using the level number as a key. Finally, print all nodes corresponding to every level starting from the last level. We can also traverse the tree in inorder or postorder fashion.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

Level 4: 30
Level 3: 8 12 16 25
Level 2: 10 20
Level 1: 15

Java


Download  Run Code

Output:

Level 4: [30]
Level 3: [8, 12, 16, 25]
Level 2: [10, 20]
Level 1: [15]

Python


Download  Run Code

Output:

Level 4: [30]
Level 3: [8, 12, 16, 25]
Level 2: [10, 20]
Level 1: [15]

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.

 
Exercise: Modify the solution to print nodes of different levels in separate lines.