In-order Tree Traversal - Iterative and Recursive

Posted by on Mar 31, 2024

Given a binary tree, the task is to write an iterative and recursive solution to perform in-order traversal on it.

Example 1: Print in-order traversal of a Binary Tree

Input:

Output: 2, 7, 5, 6, 11, 1, 9, 5, 9


Solutions

Method 1: Iteration

The in-order traversal of a binary tree can also be performed iteratively using a Stack.

Following is a simple stack-based iterative algorithm to perform in-order traversal:

s —> empty stack
  while (not s.isEmpty() or node != null)
    if (node != null)
      s.push(node)
      node —> node.left
    else
      node —> s.pop()
      visit(node)
      node —> node.right

Complexity

The time complexity of this solution is O(n) and space complexity is O(n) due to extra space required by stack.

Method 2: Recursion

In-order traversal of a tree using recursion is extremely simple and straightforward, its a three step code:

1) traverse, left of current-node
2) print current-node
3) traverse, right of current-node

if, current is null, return; this will make the base condition for this program.

Complexity

The time complexity of this solution is O(n) and space complexity is O(n) due to recursive calls.

Related


Print a Binary Tree in Vertical Order

Pre-order Tree Traversal - Iterative and Recursive

Level Order or Breadth First traversal of Binary Tree

Print Nodes in Top View of a Binary Tree

Print/Traverse a Binary Tree in Zigzag Order

Write a program to print height/depth of a Binary Tree

Find the diameter or width of a binary tree

Print the left view of a binary tree

Create a mirror tree from a given binary tree

Print diagonal traversal of a binary tree