Reverse Level Order Traversal

Objective: – Given a binary tree, Do the reverse level order traversal. In our earlier post we have seen normal Level Order Traversal. In reverse level order traversal we first need to print the last level followed by second last level up to the root, which is the first level.

Example:

Reverse Level Order Traversal Approach: Use Stack

  • Use the Queue and do the level order traversal, read “Level Order Traversal” First if you doesn’t know the technique.
  • Instead of printing the Node, keep adding it to Stack.
  • At the End print all the nodes from Stack, it will be in reverse order than normal level order traversal.

Code:


Output:

7 6 5 4 3 2 1

__________________________________________________
Top Companies Interview Questions..-

GoogleMicrosoftAmazonFacebookmore..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

4 Responses

  1. Niranjan B Subramanian says:

    should’nt the output be like this

    4 5 6 7 2 3 1

  2. Chandra Gopalaiah says:

    queue insertion order needs to be changed. First insert right child and then left child

    • tutorialhorizon says:

      Reverse level order means that we will print the last level first and then from there we will go to the root. It does not matter actually whether in a particular level which node you insert first, left or right.

      • Rakesh Venkatesh says:

        It does matter for the order in which you insert the node into stack. The nodes should always be printed from left to right

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: