Given a binary tree, perform an inorder traversal (Left → Root → Right) without using recursion or extra stack space. The goal is to achieve O(1) space complexity by modifying the tree structure temporarily.
In a standard inorder traversal, we use recursion (which requires implicit stack space) or an explicit stack to keep track of nodes.
Morris Inorder Traversal eliminates the need for extra memory by creating temporary links (threading) between nodes. These links help us traverse the tree without revisiting nodes unnecessarily.
The key idea is:
current
as the root.current
is NULL:current.left
is NULL → Print current
, move to current.right
.current.left
exists → Find the inorder predecessor (rightmost node in current.left
).predecessor.right == NULL
:predecessor.right = current
).current
to its left child.predecessor.right = NULL
).current
and move to current.right
.
public class MorrisInorderTraversal {
public static void morrisTraversal(TreeNode root) {
TreeNode current = root;
while (current != null) {
if (current.left == null) {
System.out.print(current.val + " ");
current = current.right;
} else {
// Find inorder predecessor
TreeNode predecessor = current.left;
while (predecessor.right != null && predecessor.right != current) {
predecessor = predecessor.right;
}
// Create a temporary thread
if (predecessor.right == null) {
predecessor.right = current;
current = current.left;
}
// Remove the thread and process the node
else {
predecessor.right = null;
System.out.print(current.val + " ");
current = current.right;
}
}
}
}
H
is the height of the tree. 1
/
\
2
3
/ \ / \
4 5 6 7
4 2 5 1 6 3 7
✅ O(1) Space Complexity (No recursion or extra stack)
✅ Efficient for Large Trees (Saves memory)
✅ Preserves Inorder Sequence
❌ Modifies Tree Temporarily (Requires careful restoration)
❌ Extra Pointer Manipulations (Can be tricky to implement)
Morris Inorder Traversal is a powerful technique for space-efficient binary tree traversal. It is especially useful when recursion or extra memory usage is not allowed, making it a valuable tool for technical interviews and competitive programming. 🚀
Our Program make you Job Ready for your Dream Company 🚀