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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Inorder traversal of an N-ary Tree
- Construct Special Binary Tree from given Inorder traversal
- Check if Inorder traversal of a Binary Tree is palindrome or not
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- DFS traversal of a tree using recursion
- Preorder Traversal of N-ary Tree Without Recursion
- Zig-Zag traversal of a Binary Tree using Recursion
- Find maximum and minimum element in binary tree without using recursion or stack or queue
- Find n-th node of inorder traversal
- Find all possible binary trees with given Inorder Traversal
- Print Postorder traversal from given Inorder and Preorder traversals
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Level order traversal of Binary Tree using Morris Traversal
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Construct a BST from given postorder traversal using Stack
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap