![]() |
VOOZH | about |
Given a binary tree, the task is to perform in-order traversal of the tree without using recursion.
Example:
Input:
👁 Iterative-Postorder-TraversalOutput: 4 2 5 1 3
Explanation: Inorder traversal (Left->Root->Right) of the tree is 4 2 5 1 3Input:
👁 Iterative-Postorder-Traversal-2Output: 1 7 10 8 6 10 5 6
Explanation: Inorder traversal (Left->Root->Right) of the tree is 1 7 10 8 6 10 5 6
Recap of the Inorder Traversal
The idea is to implement recursion using a stack. Starting from root node, keep on pushing the node into a stack and move to left node. When node becomes null, pop a node from the stack, print its value and move to the right node.
4 2 5 1 3
Let us do a dry run for the below tree for example:
👁 Iterative-Postorder-TraversalInitially Creates an empty stack: S = NULL and set current as address of root: current -> 1
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. Please Refer to Inorder Tree Traversal without recursion and without stack! for implementation.