Binary Tree-Inorder Traversal – Non Recursive Approach

Objective: Given a binary tree, write a non recursive or iterative algorithm for Inorder traversal.

Example:

Tree Traversals - Inorder

Earlier we have seen “What is Inorder traversal and recursive algorithm for it“, In this article we will solve it with iterative/Non Recursive manner.

Since we are not using recursion, we will use the Stack to store the traversal, we need to remember that inorder traversal is, first traverse the left node then root followed by the right node.

Pseudo Code:

  1. Create a Stack.
  2. Push the root into the stack and set the root = root.left continue till it hits the NULL.
  3. If root is null and Stack is empty Then
    1. return, we are done.
  4. Else
    1. Pop the top Node from the Stack and set it as, root = popped_Node.
    2. print the root and go right, root = root.right.
    3. Go to step 2.
  5. End If

See the animated image below and code for more understanding.

 

Inorder Traversal - Non Recursive Approach

Complete Code:

Output:

4 2 5 1 3
4 2 5 1 3

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

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...

  • swwl1992

    In the topmost picture, the in-order traversal should be “4 2 5 1 6 3 7”.
    In the Java code, the true condition can be replaced by “root != null || !nodes.isEmpty()”.

%d bloggers like this: