6.6 Threaded Binary Trees: Inorder Threading & Stackless Traversal
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy: Bookmarks Tucked Directly Inside Empty Marginsβ
Imagine walking through a huge encyclopedia using sticky bookmarks on your desk to remember where to step backward next (O(h) stack memory). Half the pages already have blank empty margins (NULL left/right pointers)! Simply pencil a tiny arrow in each empty margin pointing straight to the exact next chapter (Inorder Successor) β and you can walk the entire encyclopedia smoothly in ascending order with zero desk bookmarks (O(1) extra space)!
π» Bridging to Computer Science: Reclaiming n + 1 Null Linksβ
In any linked Binary Tree of nodes ( total pointer slots), only links hold real children, leaving exactly child pointers sitting empty as NULL! A Threaded Binary Tree (Perlis & Thornton, 1960) repoints those wasted NULL child pointers toward each node's Inorder Predecessor (left) and Inorder Successor (right), eliminating recursion & explicit stacks completely!
πTable of Contents
π§΅ Reclaiming Wasted NULL Links: Single vs. Double Threadingβ
Because a node's left or right pointer now plays dual roles (either pointing downward to a real child subtree OR looping upward along an Inorder thread), each node stores two 1-bit boolean tags lthread and rthread:
lthread == true(1):node->leftpoints to Inorder Predecessor (NULLonly for the very first Inorder node).rthread == true(1):node->rightpoints to Inorder Successor (NULLonly for the very last Inorder node).
struct ThreadedNode {
int data;
struct ThreadedNode *left, *right;
bool lthread; // true -> left points to Inorder Predecessor (not child)
bool rthread; // true -> right points to Inorder Successor (not child)
};
β‘ Stackless O(1)-Space Inorder Traversal Algorithmβ
Starting from the leftmost node (leftmost(root)), find the exact next node via inorderSuccessor(curr):
- If
curr->rthread == true: The right pointer IS directly the successor thread returncurr->rightin ! - If
curr->rthread == false: Step once right intocurr->right, then glide strictly leftmost down real left children (while (!node->lthread) node = node->left;)!
struct ThreadedNode* inorderSuccessor(struct ThreadedNode *curr) {
if (curr->rthread) return curr->right; // Instant jump via thread!
curr = curr->right;
while (!curr->lthread) curr = curr->left; // Descend to leftmost in right subtree
return curr;
}
void traverseInorderStackless(struct ThreadedNode *root) {
if (!root) return;
struct ThreadedNode *curr = root;
while (!curr->lthread) curr = curr->left; // Start at Inorder minimum
while (curr != NULL) {
printf("%d ", curr->data);
curr = inorderSuccessor(curr);
}
}
Standard Binary Tree vs. Threaded vs. Morris Traversalβ
| Traversal Strategy | Extra RAM Space | Modifies Node Structure? | Thread-Safe Reads? | Best Use Case |
|---|---|---|---|---|
| Recursive DFS | Call Stack | No | Yes | Simple general code |
| Iterative Explicit Stack | Heap Stack | No | Yes | Avoiding call-stack overflow |
| Threaded Binary Tree | Zero Stack | Stores 2 boolean thread bits | Yes (persistent threads!) | Embedded ROM/BIOS iterators & fast Inorder scans |
| Morris Traversal | Zero Stack | Mutates pointers temporarily | NO (mutates live tree!) | One-shot immutable-flag tree checks |
π Real-World Production Context: Embedded Parsers & Persistent Indexesβ
Stackless Tree Iteration in Embedded & Database Engines
When heap allocation is forbidden or pointer dereferences must eliminate auxiliary stack overhead, threading shines
Kernel & Firmware Space-Locked Iterators
Embedded RTOS / No Malloc- Real-time controllers with 4 KB stack budgets cannot risk O(n) recursive skewed-tree traversal.
- Threaded nodes guarantee strict O(1) traversal memory without malloc() inside interrupt handlers.
Ordered Index Leaf Chaining
B+ Trees / T-Trees- B+ Trees generalize right-threading by chaining all sorted leaf blocks directly with sibling pointers.
- Range scans step linearly without ever climbing back up parent branches.
Persistent Database Dictionary Cursors
Next / Prev Iterators- Iterators storing just a single node pointer move O(1) amortized forward and backward via double threading.
- Avoids maintaining an entire ancestor path array per open cursor.
π Numerical Applications & Worked Examplesβ
Consider a binary tree storing nodes constructed as a Double-Threaded Binary Tree (using both lthread and rthread, without a dummy header node):
- Out of the child pointer fields across all nodes, how many were originally
NULLbefore threading? - How many pointers remain
NULLeven after double-threading completes (without a dummy header)? - Given node
XwithX->lthread = falseandX->right = YwhereY->rthread = true, ifX->rthread = true, where doesX->rightpoint?
Step-by-Step Solution:β
-
Original
NULLCount (n = 15): Total pointer slots . Non-null real child links . Thus originallyNULLslots . -
Remaining
NULLSlots After Double Threading: Every reclaimedNULLpoints to an Inorder predecessor or successor β ONLY 2 nodes lack one neighbor:- The smallest (first Inorder) node has zero Inorder predecessor (
left = NULL). - The largest (last Inorder) node has zero Inorder successor (
right = NULL). - Exactly slots become threads, leaving strictly
NULLpointers (or if closed via a Dummy Header sentinel!).
- The smallest (first Inorder) node has zero Inorder predecessor (
-
Thread Direction Rule: Because
X->rthread == true,X->right(Y) points directly toX's Inorder Successor (not a right child subtree!).
π― Exam & Interview Pitfall Checkβ
- In a Right-Only Single-Threaded Binary Tree (
rthreadonly), what traversal direction runs in stack space?- Forward Inorder (
L -> N -> R) runs cleanly viarightsuccessor threads; reverse Inorder (R -> N -> L) would needlthreadpredecessor threads (Double Threading)!
- Forward Inorder (
- Why do real-world implementations pair Threaded Binary Trees with a Dummy Header Node?
- Connecting the first leaf's
leftand last leaf'srightonto a permanent Header Node turns the tree into a closed ring with ZERONULLchecks needed anywhere inside insertion/traversal!
- Connecting the first leaf's
- Forgetting
if (curr->lthread)Guard During Traversal Descent: Stepping blindlywhile (curr->left != NULL) curr = curr->left;in a threaded tree chases thread pointers backward infinitely, hanging forever! Always checkwhile (!curr->lthread), NEVERcurr->left != NULL! - Skipping Thread Updates During BST Insert/Delete: Inserting a new left child
Nunder parentPMUST inheritP's oldlthreadpredecessor (N->left = P->left; N->lthread = true; N->right = P; N->rthread = true; P->left = N; P->lthread = false;) β missing one flag breaks downstream walks permanently! - Using Standard Recursion on a Threaded Tree Without Checking Flags: Calling
inorder(node->left)blindly traverses thread loops upward infinitely!
π Navigation & Next Stepsβ
Next, we tackle the height skew problem directly using strict balance factors and rotations in Topic 6.7 β AVL Trees: Balance Factors and the 4 Rotation Invariants.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.