Inorder Tree Traversal without recursion and without stack ?
- To traverse the tree using Morris Traversal is based on Threaded Binary Tree which means without using stack and recursion. 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.
-
- If current does not have left child
- Print current’s data
- Go to the right, i.e., current = current->right
- If current does not have left child
-
- Else
- Make current as right child of the rightmost
- node in current’s left subtree
- Go to this left child, i.e., current = current->left
- Else
- When 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.
Sample Code in C++
Output
- Time Complexity : O(n) If we investigate, we can see that each edge of the tree is crossed at-most multiple times.
- Also, in most pessimistic scenario same number of additional edges (as info tree) are made and evacuated.