Reverse Level Order Traversal of a Binary Tree

Given a binary tree, write a code to print its reverse level order traversal.

For example:

The reverse or bottom-up level order traversal of this binary tree is 4, 3, 2, 1, 6, 5, 7.

In this example, first we printed last level then second last level and so on. So, we have to start printing the level from bottom-up.

This problem is similar to the level order traversal of a binary tree except in this problem we have to print the level in reverse order.

How we can solve this problem? What’s the time and space complexity of our approach?

Print right view of a binary tree

Programming video tutorials

Reverse Level Order Traversal of a Binary Tree

Reverse Level Order Traversal of a Binary Tree – Java Code

Let’s first discuss the algorithm and then we will write it’s java code. To solve this problem we need two data structure stack and queue.

i) Declare a queue and stack and add root node in a queue.


ii) Run a while loop while the queue is not empty and do the following steps
a) poll a queue and add the node data in a stack.
b) Enqueue (insert in a queue) right and left children of a node if it’s not null.

iii) In the end, traverse a stack and print it’s node data.

The time complexity of this approach is O(n) and its space complexity is also O(n).

In this video tutorial, I have explained how to print level order traversal in reverse order using queue and stack data structure.

If you know any other approach which solves this problem efficiently, then let us know through your comment.

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.