Reference_GeeksforGeeks
Thread Binary Tree
Inorder Tree Traversal without recursion and without stack
Using Morris Travesal
, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree
.
In this traveral, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree.
- Initalize current as root
- While current is not NULL
If the current does not have left child
Else1. Print current's data 2. Go to the right, i.e., current = current->right
Find rightmost node in current left subtree `OR` node whose right child == current *If* we found right child == current Go to the right, i.e. current = current->right *Else* 1. Make current as the right child of that rightmost node we found; and 2. Go to this left child, i.e., current = current -> current->left
Although the tree is modified through the traversal, it is reverted back to its original shape after the completion. No extra space is required
1 | struct tNode{ |