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.
- 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
- Construct Special Binary Tree from given Inorder traversal
- DFS traversal of a tree using recursion
- Preorder Traversal of N-ary Tree Without Recursion
- 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
- Construct a BST from given postorder traversal using Stack
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Level order traversal in spiral form | Using one stack and one queue
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Inorder Successor of a node in Binary Tree