Chapter 12: Threaded Binary Trees
Introduction
Learning Outcomes
Prove that a binary tree with n nodes has n+1 NULL pointers.
Apply the rule: left NULL → inorder predecessor, right NULL → inorder successor.
Define the structure fully with the left_thread / right_thread flags and a head node.
Traverse inorder (and preorder) with insucc using O(1) extra space.
Merge the two cases of insert_right into one routine; derive insert_left.
A clearly defined routine, a meaningful comment, the right place for the NULL check.
Why Threads?
n+1 NULL pointers in n nodes
- Each node has 2 pointer fields → 2n pointers in the tree.
- Every node except the root is pointed to by its parent → n − 1 pointers are used.
- The remaining 2n − (n−1) = n + 1 pointers are NULL: more than half the pointers are wasted!
— Alan J. Perlis
Short dashed lines are NULL pointers; in all three examples there are n + 1 of them.
Why Threads?
The idea: make the null pointers point the way
- A. J. Perlis and C. Thornton showed that NULL pointers can be used to point to other nodes of the tree; they called these pointers threads.
- The gain: an inorder traversal needs no stack and no recursion; from each node we go straight to its successor.
- The price: one bit per pointer saying whether it is a child or a thread.
Threading Rules
Rules for building a threaded binary tree
- If
p->left_child == NULL,p->left_childpoints to the node visited just before p in inorder: the NULL is replaced by p's inorder predecessor. - If
p->right_child == NULL,p->right_childpoints to the node visited just after p: the NULL is replaced by p's inorder successor.
The dashed red arrows are threads. They “weave” the tree's inorder sequence into the tree itself.
Threading Rules
Adding the threads one by one
An ordinary binary tree: 9 nodes, 10 NULL pointers (dashed). Inorder: H D I B E A F C G.
H's left pointer is NULL → it points to its inorder predecessor, but none exists: it dangles until the head node is added.
H's right pointer is NULL → it points to its inorder successor, D.
I's left pointer is NULL → it points to its inorder predecessor, D.
I's right pointer is NULL → it points to its inorder successor, B.
E's left pointer is NULL → it points to its inorder predecessor, B.
E's right pointer is NULL → it points to its inorder successor, A.
F's left pointer is NULL → it points to its inorder predecessor, A.
F's right pointer is NULL → it points to its inorder successor, C.
G's left pointer is NULL → it points to its inorder predecessor, C.
G's right pointer is NULL → it points to its inorder successor, but none exists: it dangles until the head node is added.
Threading Rules
How do we tell the compiler an arrow is red?
typedef struct threaded_tree *thread_ptr; struct threaded_tree { short int left_thread; /* TRUE: thread */ thread_ptr left_child; char data; thread_ptr right_child; short int right_thread; /* TRUE: thread */ };
A struct definition ends with the closing ; (line 8); forgetting it is a common mistake. TRUE/FALSE: enum { FALSE, TRUE }.
Threading Rules
Two dangling threads and the head node
- H's left thread and G's right thread have nothing to point to: they dangle.
- We add a head node: the root of the actual tree is reached through
L->left_child. - The two dangling threads point to the head; the head's right pointer always points to itself, with right thread FALSE.
- In an empty tree the left pointer also points to the head, with left thread TRUE; it becomes FALSE once a node is inserted.
| left_thread | left_child | data | right_child | right_thread |
|---|---|---|---|---|
| TRUE | → head | – | → head | FALSE |
An empty threaded tree
Threading Rules
The head node: empty tree and nonempty tree
Empty tree: only the head; both of its pointers point to itself.
Nonempty tree: the head's left points to the root (A); H's left thread and G's right thread are tied to the head. T/F: the thread flags.
Threading Rules
The tree is threaded for inorder traversal
| traversal | order |
|---|---|
| inorder | H D I B E A F C G |
| preorder | A B D H I E C F G |
| postorder | H I D E B F G C A |
Threads follow inorder predecessors and successors; preorder and postorder traversals can also be done with them (more circuitously).
Inorder Traversal
Finding the inorder successor
- If
p->right_thread == TRUE,p->right_child(being a thread) already is p's successor. - If
p->right_thread == FALSE, start at the right child and followleft_childlinks untilleft_threadis TRUE: the leftmost node of the right subtree is the successor.
thread_ptr insucc(thread_ptr L) {
// successor of the (non-NULL) node L
thread_ptr p = L->right_child;
if (!L->right_thread) // right subtree?
while (!p->left_thread) // go to its leftmost
p = p->left_child;
return p;
}Inorder Traversal · Run the code step by step
insucc(): for the head, A and I
insucc(head): p = head->right_child = head.
right_thread is FALSE: the head has a real right subtree; the successor is its leftmost node.
head->left_thread FALSE → go left: p = A.
A->left_thread FALSE → go left: p = B.
B->left_thread FALSE → go left: p = D.
D->left_thread FALSE → go left: p = H.
H->left_thread TRUE: cannot go further left → the leftmost node.
Returns H: the head's inorder successor. (The head's successor = the first node visited.)
insucc(A): p = A->right_child = C.
right_thread is FALSE: A has a real right subtree; the successor is its leftmost node.
C->left_thread FALSE → go left: p = F.
F->left_thread TRUE: cannot go further left → the leftmost node.
Returns F: A's inorder successor.
insucc(I): p = I->right_child = B.
I's right pointer is a thread (TRUE): the successor is B directly. The loop is skipped.
Returns B: I's inorder successor.
thread_ptr insucc(thread_ptr L) {
// successor of the (non-NULL) node L
thread_ptr p = L->right_child;
if (!L->right_thread) // right subtree?
while (!p->left_thread) // go to its leftmost
p = p->left_child;
return p;
}Inorder Traversal · Run the code step by step
tinorder(): – H D I B E A F C G –
p = L: start at the head. No stack, no recursion; one pointer is enough.
p = succ(head) = H (leftmost of the right subtree); printed.
p = succ(H) = D (directly via the thread); printed.
p = succ(D) = I (leftmost of the right subtree); printed.
p = succ(I) = B (directly via the thread); printed.
p = succ(B) = E (leftmost of the right subtree); printed.
p = succ(E) = A (directly via the thread); printed.
p = succ(A) = F (leftmost of the right subtree); printed.
p = succ(F) = C (directly via the thread); printed.
p = succ(C) = G (leftmost of the right subtree); printed.
G's successor (directly via the thread) is the head: the traversal is done → break.
void tinorder(thread_ptr L) { thread_ptr p = L; // L: the head node for (;;) { p = insucc(p); if (p == L) break; // back at the head? printf("%c ", p->data); } }
Inorder Traversal
The cost of threaded traversal
- Each thread and each real left/right link is followed at most once → O(n) time.
- Extra space O(1): just the pointer p (recursive traversal needs an O(h) call stack, iterative an O(h) stack).
- From any node we can move to its successor without restarting the traversal.
To strip the line numbers from code listings, hold ALT in the editor, select the column and press DEL.
Inorder Traversal · Run the code step by step
Preorder traversal with the same threads
succ(head) = A (left child).
succ(A) = B (left child).
succ(B) = D (left child).
succ(D) = H (left child).
succ(H) = I (right child reached via the right threads through D).
succ(I) = E (right child reached via the right threads through B).
succ(E) = C (right child reached via the right threads through A).
succ(C) = F (left child).
succ(F) = G (right child reached via the right threads through C).
G: following the right threads leads to the head → head: the traversal ends.
thread_ptr presucc(thread_ptr p) {
if (!p->left_thread) // left child if any
return p->left_child;
while (p->right_thread) // climb the threads
p = p->right_child;
return p->right_child; // first real child
}If there is a left child, it is the successor; otherwise climb the right threads and step to the first real right child. Postorder needs parent information (harder).
Inorder Traversal
Morris traversal: temporary threads
void morris_inorder(tree_ptr L) { while (L) { if (!L->left) { /* no left: print, right */ printf("%c", L->data); L = L->right; } else { tree_ptr p = L->left; /* inorder predecessor */ while (p->right && p->right != L) p = p->right; if (!p->right) { /* add a temp thread */ p->right = L; L = L->left; } else { /* remove the thread */ p->right = NULL; printf("%c", L->data); L = L->right; } } } }
J. M. Morris (1979). No flag fields needed: threads are added and removed during the traversal; since the tree changes meanwhile, it is unsafe for concurrent readers.
Inorder Traversal
Morris traversal step by step: A(B(D,E),C)
Start: no stack. At each node with a left subtree, a temporary thread goes into its predecessor's (empty) right pointer.
A's predecessor is E; its right is empty → add thread E → A, go left.
B's predecessor is D; its right is empty → add thread D → B, go left.
D has no left: print it, go right (or along the temporary thread) → B.
Back at B through the thread from its predecessor D: remove the thread, print B, go right.
E has no left: print it, go right (or along the temporary thread) → A.
Back at A through the thread from its predecessor E: remove the thread, print A, go right.
C has no left: print it, go right (or along the temporary thread) → NULL.
Done: DBEAC. The tree is restored; extra space O(1), time O(n).
Inserting a Node
Inserting a node into a threaded tree
- Insertion is not a simple routine on its own; it is a bit tricky.
- Inserting to the right and to the left differ → two routines:
insert_right,insert_left. - Inserting to the right has two cases: (1) the parent has no right subtree, (2) it has one.
- In a BST, insertion was a single assignment at an empty child slot; here the threads (red arrows) must also point to the right places.
child->right_child = parent->right_child; child->right_thread = TRUE; // parent: no right child->left_child = parent; child->left_thread = TRUE; parent->right_child = child; parent->right_thread = FALSE; // was TRUE
Case 1: insertion in 6 assignments.
Inserting a Node · Run the code step by step
Case 1: inserting under a parent with no right subtree
child->right_child = parent->right_child: the parent's right thread (its successor) moves to the child. (Whether it is the head does not matter.)
child->right_thread = TRUE: the parent had no subtree, so the child cannot either → red arrow.
child->left_child = parent: the child's inorder predecessor is the parent.
child->left_thread = TRUE: this is a thread too (red).
parent->right_child = child: a real (black) link from parent to child.
parent->right_thread = FALSE: the parent's right is now the child, not a thread. Done: 6 assignments.
child->right_child = parent->right_child; child->right_thread = TRUE; // parent: no right child->left_child = parent; child->left_thread = TRUE; parent->right_child = child; parent->right_thread = FALSE; // was TRUE
Inserting a Node
Case 2: the parent has a right subtree
- Goal: D is B's child, and we make X B's child instead; but the D subtree must not be lost, and the red pointers must still point to the right places.
- X's predecessor becomes B. E, the leftmost node of the D subtree, used to have B as its predecessor; now E is X's successor.
- So: the child must become the predecessor of the parent's old successor.
- In the case 2 code, line 2 is
child->right_thread = FALSE(the parent's subtree is now the child's); E's left thread must also be fixed.
child->right_thread = parent->right_thread, we get a single routine that handles both cases.Inserting a Node · Run the code step by step
insert_right(B, X): one routine, case 2
child->right_child = parent->right_child: B's old right subtree (D) goes to X's right.
child->right_thread = parent->right_thread (FALSE): the parent's subtree is now the child's; the link stays black.
child->left_child = parent: X's predecessor is B.
child->left_thread = TRUE: red arrow.
parent->right_child = child: real link B → X.
parent->right_thread = FALSE: it was FALSE already; needed for case 1, harmless here. “Don't conclude too soon that the code works!”
child->right_thread FALSE → X has a right subtree: the left thread of X's successor still points to B and must be fixed.
p = insucc(X) = E (leftmost of D). E's old predecessor was B.
p->left_child = child: E's left thread now points to X. The child became the predecessor of the parent's old successor.
void insert_right(thread_ptr parent, thread_ptr child) { // make child the right child of parent thread_ptr p; child->right_child = parent->right_child; child->right_thread = parent->right_thread; child->left_child = parent; child->left_thread = TRUE; parent->right_child = child; parent->right_thread = FALSE; if (!child->right_thread) { // parent had a subtree? p = insucc(child); p->left_child = child; // succ's pred is child } }
Inserting a Node
insert_right line by line
Clear name, clear parameters, clear return value.
The child's right pointer and right thread come from the parent: red (TRUE) is kept in case 1, black (FALSE) in case 2.
The child's inorder predecessor is the parent: left pointer to the parent, left thread TRUE (red).
FALSE into the parent's right thread: needless but harmless in case 2; required in case 1.
If the child's right thread is FALSE (case 2), the successor's left thread is redirected to the child; in case 1 it is one test and return.
C is case-sensitive: parent->Right_child, parent->Right_thread (capital R) do not compile. The condition checks whether the parent has a right child.
Inserting a Node
Where should the NULL check go?
- Example: when inserting into a threaded search tree, once we know whether to go right or left, we call
insert_rightorinsert_leftinstead of a single assignment; the parent is never NULL. - If the routine does not check its inputs, the comment must say so: “parent and child must not be NULL”.
- A general library routine adds defensive checks (
assertor an error return).
Inserting a Node
What should a comment say?
/* BAD: repeats the code */ if (!child->right_thread) // right thread FALSE? /* GOOD: states intent */ if (!child->right_thread) // parent had a subtree?
- A comment should say what the code means to do; it should not repeat the code.
- Then a reader can say “the intent is right but the code is wrong”: debugging gets easier.
Inserting a Node
Reducing to one routine, and software engineering
- First analyze the 3–5 different cases; then decide the routine's name, return value and parameters.
- Define the common work in a common way (here: copying the thread flag from the parent).
- Result: code that is not fragmented; simple, readable, easy to maintain.
Inserting a Node
QUESTION: think about the insert-left routine
Write insert_left, which inserts the node pointed to by child into the threaded tree as the left child of parent.
- Left ↔ right and predecessor ↔ successor swap: the parent's old predecessor becomes the child's predecessor, and its right thread is redirected to the child.
- Finding the inorder predecessor: the rightmost node of the left subtree if there is one, else the left thread.
Inserting a Node
Solution: insert_left and inpred
thread_ptr inpred(thread_ptr L) {
thread_ptr p = L->left_child;
if (!L->left_thread)
while (!p->right_thread) p = p->right_child;
return p;
}
void insert_left(thread_ptr parent, thread_ptr child) {
child->left_child = parent->left_child;
child->left_thread = parent->left_thread;
child->right_child = parent;
child->right_thread = TRUE; // successor: parent
parent->left_child = child;
parent->left_thread = FALSE;
if (!child->left_thread) { // parent had a left subtree
thread_ptr p = inpred(child);
p->right_child = child; // pred's succ is child
}
}Inserting a Node
Stay alert when coding!
Threaded tree
- Stackless traversal in O(1) space
- Successor/predecessor of any node in O(h), amortized O(1) during traversal
- NULL fields are not wasted
The price
- 2 flags per node
- Insert/delete are trickier
- Every routine must maintain the threads
Lab · C code step by step
Lab: Threaded Inorder Traversal
Summary
Complexity summary
| operation | time | extra space | note |
|---|---|---|---|
| insucc | O(h) worst case | O(1) | O(1) if a thread |
| tinorder | O(n) | O(1) | no stack / recursion |
| threaded preorder traversal | O(n) | O(1) | same threads |
| insert_right / insert_left | O(h) | O(1) | successor/predecessor search |
| Morris traversal (no flags) | O(n) | O(1) | temporary threads |
| recursive inorder (for comparison) | O(n) | O(h) | call stack |
Summary
Common mistakes
left_child/right_child for a real child without checking the thread flag (infinite loop).child->right_thread as TRUE and breaking case 2.left_thread = TRUE.Right_child ≠ right_child (C is case-sensitive).Summary
Exercises
- Draw the threads of the tree A(B(D, E), C(–, F)); how many threads are there?
- Write
inpred, which finds the inorder predecessor. - Write a routine that traverses a threaded tree in reverse inorder (G C F A …).
- Is it correct to insert the first node into an empty tree (just the head) with
insert_left(head, x)? - Why is postorder traversal hard with threads? What extra information makes it easy?
- Write insertion into a threaded binary search tree using
insert_right/insert_left.
Hints / answers
- n = 6 → n + 1 = 7 threads (2 of them to the head).
- The mirror of finding the successor: if the left thread is TRUE, directly; otherwise go to the left child and then right, right (see the insert-left solution).
- Start at the head; move with
inpreduntil you are back at the head. - Yes: since the head's left thread is TRUE, the child points to the head with both threads, and the head's left_thread becomes FALSE.
- A node's postorder successor depends on its parent; adding a
parentpointer makes it easy. - Search: stop where the thread flag is TRUE; if x is smaller call
insert_left, if largerinsert_right.
Summary
Chapter summary
n−1 of the 2n pointers are used; the rest become threads.
Left NULL → predecessor, right NULL → successor; flags tell them apart; the head collects the dangling threads.
Directly if the right thread is TRUE; otherwise the leftmost node of the right subtree.
Stackless, O(n) time, O(1) space; preorder works too.
insert_right: the thread flag is copied from the parent; in case 2 the child becomes the successor's predecessor.
Clear definition, meaningful comments, the right place for the NULL check, one routine.
Summary
References and next steps
- Horowitz–Sahni–Anderson-Freed, Fundamentals of Data Structures in C, 5.5 Threaded Binary Trees.
- A. J. Perlis, C. Thornton, “Symbol manipulation by threaded lists”, CACM 3(4), 1960.
- J. M. Morris, “Traversing binary trees simply and cheaply”, Information Processing Letters 9(5), 1979; Knuth, TAOCP 1, 2.3.1.