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.
1. Initialize current as root 2. While current is not NULL If the current does not have left child a) Print current’s data b) Go to the right, i.e., current = current->right Else a) Make current as the right child of the rightmost node in current's left subtree b) Go to this left child, i.e., current = current->left
Although the tree is modified through the traversal, it is reverted back to its original shape after the completion. Unlike Stack based traversal, no extra space is required for this traversal.
4 2 5 1 3
Time Complexity : O(n) If we take a closer look, we can notice that every edge of the tree is traversed at most two times. And in the worst case, the same number of extra edges (as input tree) are created and removed.
Please write comments if you find any bug in above code/algorithm, or want to share more information about stack Morris Inorder Tree Traversal.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Inorder Tree Traversal without Recursion
- Postorder traversal of Binary Tree without recursion and without stack
- Cartesian tree from inorder traversal | Segment Tree
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Preorder Traversal of N-ary Tree Without Recursion
- Find maximum and minimum element in binary tree without using recursion or stack or queue
- Construct Special Binary Tree from given Inorder traversal
- Inorder traversal of an N-ary Tree
- Check if Inorder traversal of a Binary Tree is palindrome or not
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Print Postorder traversal from given Inorder and Preorder traversals
- Find all possible binary trees with given Inorder Traversal
- Find n-th node of inorder traversal
- DFS traversal of a tree using recursion
- Zig-Zag traversal of a Binary Tree using Recursion
- Level order traversal of Binary Tree using Morris Traversal
- Tree Traversals (Inorder, Preorder and Postorder)
- Construct Tree from given Inorder and Preorder traversals
- Construct a tree from Inorder and Level order traversals | Set 1