Binary Tree Inorder Traversal without Recursion using Stack

In this tutorial, I am going to discuss binary tree inorder traversal without recursion.

Given a binary tree, write a code to print the Inorder traversal of a binary tree node values.

What is Binary Tree Inorder Traversal?

Traversing a tree means visiting each node of the tree exactly once. In inorder traversal, we visit the tree in following order.

i) Visit all the nodes of the left subtree.

ii) Visit root node.

iii) Visit all the nodes of the right subtree.

For example-

The Inorder traversal of given binary tree is 4, 6, 3, 7, 2, 5, 1.

Binary Tree Inorder traversal without recursion
Binary Tree Inorder traversal without recursion

Remember, we don’t have to use recursion. So, how do we print Inorder traversal of a binary tree using iterative approach. Do we need to use any additional data structure? Which data structure should we use?

Before writing, the iterative code of a binary tree inorder traversal. Let’s write it’s recursive version first.

To write it’s iterative version, which data structure should we use. Definitely, we use Stack for implementing inorder traversal without recursion.

Left view of a binary tree

Right view of a binary tree

Binary tree inorder traversal

Binary Tree Inorder Traversal using Stack – Algorithm

Let’s understand the algorithm of inorder traversal without recursion.

i) Declare an empty stack.

ii) Push the root node value into a stack and set root = root.left until root is not null.

So, in stack following value is pushed.

First operation is to Push 7, Now the value of Stack is S -> 7

In next step, Push 6, Stack S -> 7, 6

Push 4: Stack S -> 7, 6, 4

After this operation root node points to null. No further node is going to push.

iii) In next step, pop the value from stack. Print it’s value. Then, assign root to temp.right.

iv) Repeat step ii and iii until stack is empty or root is NULL.

Programming video tutorials on binary tree

Check if two binary trees are identical

Cousins In Binary Tree

Binary Tree Inorder Traversal without Recursion – Java Code

Let’s write a java code to implement Inorder traversal using stack.

Level Order Traversal of a Binary Tree

Binary tree preorder traversal

Binary Tree Inorder Traversal LeetCode Solution

LeetCode solution of a Binary Tree inorder traversal using stack.

Binary Tree Level Order Traversal

Tagged , , , . Bookmark the permalink.

About WebRewrite

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