Morris Traversal is a method for traversing binary trees without using any extra space for storing information about nodes. It allows for the traversal of a binary tree in Inorder, Preorder, and Postorder without recursion or using a stack.
Introduction
Morris Traversal is an elegant and efficient algorithm for traversing binary trees. It was introduced by J. H. Morris in 1979. The key idea behind Morris Traversal is to modify the tree as we traverse it so that we can navigate through the nodes without using any additional space for a stack or recursion. This method helps to reduce the space complexity of tree traversal algorithms.
Pseudo Code
The general idea behind Morris Traversal is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1. Initialize current as root 2. While current is not NULL a. If current does not have a left child i. Print current's data ii. Move to the right child (current = current->right) b. Else i. Find the inorder predecessor of current (say it's the rightmost node in current's left subtree, and cannot be current node) ii. If the right child of the predecessor is NULL 1. Set the right child of the predecessor to current (Creating temp links) 2. Move current to its left child (current = current->left) iii. Else 1. Set the right child of the predecessor back to NULL (Removing temp links) 2. Print current's data 3. Move current to its right child (current = current->right)
This main driver code constructs a binary tree, then applies each of the Morris Traversal methods (inorder, preorder, postorder) to print the traversals. Finally, it deallocates the memory allocated for the tree nodes.