Reverse level order traversal of binary tree in java

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.

This is part of java binary tree tutorial.
In this post, we will see about Reverse Level Order binary tree traversal in java. In previous post, we have already seen Level order traversal. In reverse level order traversal, we will visit last level first, then second last and eventually first level.

Reverse Level Order traversal:

Reverse Level order traversal of below binary tree will be:

We will use stack  for Reverse Level Order traversal.

Steps for Reverse Level order traversal algorithm:

  1. Create empty queue and push root node to it.
  2. Do the following when queue is not empty
    • Pop a node from queue and print it
    • Push right child of popped node to queue if not null
    • Push left child of popped node to queue if not null
    • Push popped node to stack
  3. Pop node from stack and print it
Example:
Lets say your binary tree is :

So Reverse Level Order traversal will work as below:

Lets create java program :

Run above program and you will get following output:

Reverse Level Order traversal of binary tree will be:
10 30 50 70 20 60 40

Java Binary tree tutorial

Please go through java interview programs for more such programs.

Was this post helpful?

Comments

  1. Great post, thanks for writing this material

    There is a small mistake, you have as a first step in algorithm “Pop a node from queue and print it”
    I'm guessing that's a typo or copy and paste from level order traversal

Leave a Reply

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