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 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 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 worst case 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.
- Threaded Binary Tree
- Print Postorder traversal from given Inorder and Preorder traversals
- Reverse Level Order Traversal
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Morris traversal for Preorder
- Iterative Preorder Traversal
- Construct Tree from given Inorder and Preorder traversals
- Root to leaf path sum equal to a given number
- Inorder Tree Traversal without Recursion
- Level Order Tree Traversal
- If you are given two traversal sequences, can you construct the binary tree?
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Calculate Size of a tree | Recursion
- Tree Traversals (Inorder, Preorder and Postorder)