AlgoMaster Logo

Binary Tree Inorder Traversal

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

Intuition:

In an inorder traversal, we visit the left subtree first, then the root, and finally the right subtree. The recursive approach is a direct and simple way to implement this traversal. We can use a recursive function to traverse the left subtree, visit the root node, and then traverse the right subtree.

Code:

2. Iterative Approach with Stack

Intuition:

Instead of using the system's call stack which the recursive approach does implicitly, we can use an explicit stack to simulate the traversal. This approach iteratively manages the nodes to be processed by continuously traversing the left while recording nodes on the stack. When it reaches a node without a left child, it pops from the stack and moves to the right subtree.

Code:

3. Morris Traversal

Intuition:

Morris Traversal provides a way to perform the inorder traversal without extra space. The idea is to temporarily make a link from the rightmost node of left subtree to the root node, which allows us to traverse without a stack. After visiting, we have to restore the tree back to its original structure.

Code: