Recursion hides a stack: the call stack (Unit 4). We can make that stack explicit and write traversals as loops. Or we can avoid a stack completely by storing extra links, called threads, in the tree. This page does both.
Preorder with an explicit stack
Push the root (if the tree is not empty).
While the stack is not empty: pop a node v v v , visit it, push v v v ‘s right child if it exists, then push its left child if it exists.
The right child is pushed first so that the left child is on top and is processed first.
Inorder with an explicit stack
Intuition
Walking down a staircase of left children, you drop a marker on every step. At the bottom you visit the node, then go one step to the right and walk down its left staircase again. When there is nowhere to go, pick up the most recent marker and continue from there.
Set cur = root.
While cur is not NULL or the stack is not empty:
while cur is not NULL: push cur, set cur = cur->left;
pop a node, visit it, and set cur to its right child.
Example 6.13 Iterative preorder and inorder of Figure 6.16
Goal. Traverse the tree of Figure 6.16 without recursion and record the largest stack size in preorder.
Program.
C · iterative.c Copy #include <stdio.h>
#include <stdlib.h>
typedef struct node {
struct node * left;
char value;
struct node * right;
} Node;
Node * make( char v, Node * l, Node * r)
{
Node * n = malloc( sizeof * n);
if (n == NULL ) {
fprintf(stderr, "out of memory \n " );
exit(EXIT_FAILURE);
}
n->value = v; n->left = l; n->right = r;
return n;
}
#define MAXSTACK 64
/* Preorder with an explicit stack: visit, then push right, then left,
so the left subtree is popped (and visited) first. NULLs are not pushed. */
void preorder_iter(Node * root)
{
Node * stack[MAXSTACK];
int top = - 1 , max_used = 0 ;
if (root != NULL )
stack[ ++ top] = root;
while (top >= 0 ) {
Node * v = stack[top -- ];
printf( "%c " , v->value);
if (v->right) stack[ ++ top] = v->right;
if (v->left) stack[ ++ top] = v->left;
if (top + 1 > max_used) max_used = top + 1 ;
}
printf( " (largest stack size %d) \n " , max_used);
}
/* Inorder with an explicit stack: go left as far as possible, pushing
each node; pop one, visit it, then continue with its right subtree. */
void inorder_iter(Node * root)
{
Node * stack[MAXSTACK];
int top = - 1 ;
Node * cur = root;
while (cur != NULL || top >= 0 ) {
while (cur != NULL ) { /* walk down the left side */
stack[ ++ top] = cur;
cur = cur->left;
}
cur = stack[top -- ]; /* leftmost unvisited node */
printf( "%c " , cur->value);
cur = cur->right; /* now do its right subtree */
}
printf( " \n " );
}
void free_tree(Node * t)
{
if (t == NULL ) return ;
free_tree(t->left);
free_tree(t->right);
free(t);
}
int main( void )
{
Node * root = make( 'A' ,
make( 'B' ,
make( 'D' , make( 'G' , NULL , NULL ), make( 'H' , NULL , NULL )),
make( 'E' , make( 'I' , NULL , NULL ), make( 'J' , NULL , NULL ))),
make( 'C' , NULL , NULL ));
printf( "iterative preorder: " );
preorder_iter(root);
printf( "iterative inorder : " );
inorder_iter(root);
free_tree(root);
return 0 ;
}
Run it.
Output Copy iterative preorder: A B D G H E I J C (largest stack size 4)
iterative inorder : G D H B I E J A C
Result. The loops give the same orders as the recursive functions; preorder never held more than 4 nodes on its stack.
Correction · Program 6.5 (non-recursive preorder)
Study material says: The algorithm in §6.7.2 checks “if v is not NULL” after popping, but Program 6.5 pops tree, calls visit(tree) and then pushes tree->right and tree->left without any NULL check.
Correct version: Either push only non-NULL children (if (v->right) push(v->right); if (v->left) push(v->left);), as in the program above, or skip NULL nodes after popping, as the algorithm says. Also push the root only if the tree is not empty.
Why: Every leaf has NULL children, so Program 6.5 pushes NULL, later pops it and calls visit(NULL) and NULL->right, which is undefined behaviour (a crash on most systems).
Threaded binary trees
A binary tree with n n n nodes has n + 1 n + 1 n + 1 NULL links. A threaded binary tree puts these unused links to work: a NULL right link is replaced by a thread to the node’s inorder successor (and, in a fully threaded tree, a NULL left link by a thread to its inorder predecessor). A one-bit flag in each node says whether the link is a real child or a thread.
Node of a right-threaded binary tree Copy struct tnode {
struct tnode *left;
int value;
struct tnode *right; /* right child, or thread to the inorder successor */
bool rthread; /* true if right is a thread */
};
Inorder traversal then needs no stack: start at the leftmost node; after visiting a node, if its right link is a thread, follow it; otherwise go to the leftmost node of its right subtree.
Example 6.14 Inorder traversal through threads
Goal. Add right threads to the tree of Figure 6.16 and traverse it in inorder without a stack, printing each thread used.
Program. make_threads sets every NULL right link to the inorder successor; the last node in inorder keeps NULL.
C · threaded.c Copy #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/* Right-threaded binary tree: if a node has no right child, its right
pointer is a THREAD to its inorder successor, marked by rthread = true. */
typedef struct tnode {
struct tnode * left;
char value;
struct tnode * right;
bool rthread; /* true: right is a thread, not a child */
} TNode;
TNode * make( char v, TNode * l, TNode * r)
{
TNode * n = malloc( sizeof * n);
if (n == NULL ) {
fprintf(stderr, "out of memory \n " );
exit(EXIT_FAILURE);
}
n->value = v; n->left = l; n->right = r; n->rthread = false ;
return n;
}
/* Replace every NULL right pointer by a thread to the inorder successor.
prev is the node visited just before t in inorder. */
void make_threads(TNode * t, TNode ** prev)
{
if (t == NULL ) return ;
make_threads(t->left, prev);
if ( * prev != NULL && ( * prev)->right == NULL ) {
( * prev)->right = t; /* thread: prev's successor is t */
( * prev)->rthread = true ;
}
* prev = t;
if ( ! t->rthread)
make_threads(t->right, prev);
}
TNode * leftmost(TNode * n)
{
while (n != NULL && n->left != NULL )
n = n->left;
return n;
}
/* Inorder traversal with no stack and no recursion. */
void inorder_threaded(TNode * root)
{
TNode * cur = leftmost(root);
while (cur != NULL ) {
printf( "%c" , cur->value);
if (cur->rthread) {
printf( "(thread->%c) " , cur->right->value);
cur = cur->right; /* follow the thread up */
} else {
printf( " " );
cur = leftmost(cur->right); /* go to the right subtree */
}
}
printf( " \n " );
}
void free_tree(TNode * t)
{
if (t == NULL ) return ;
free_tree(t->left);
if ( ! t->rthread)
free_tree(t->right);
free(t);
}
int main( void )
{
TNode * root = make( 'A' ,
make( 'B' ,
make( 'D' , make( 'G' , NULL , NULL ), make( 'H' , NULL , NULL )),
make( 'E' , make( 'I' , NULL , NULL ), make( 'J' , NULL , NULL ))),
make( 'C' , NULL , NULL ));
TNode * prev = NULL ;
make_threads(root, & prev);
printf( "inorder via threads: " );
inorder_threaded(root);
free_tree(root);
return 0 ;
}
Run it.
Output Copy inorder via threads: G(thread->D) D H(thread->B) B I(thread->E) E J(thread->A) A C
Result. The traversal G D H B I E J A C is produced with no stack and no recursion; the threads G→D, H→B, I→E and J→A lead back up the tree.
Correction · How threaded binary trees work
Study material says: §6.7.2 says that traversing without a stack “requires pointers to the parent node (called threaded binary tree)”, and gives a node with a fourth field struct NODE *thread; /* third pointer to it's inorder successor */.
Correct version: A threaded binary tree does not use parent pointers or an extra pointer field. It reuses the NULL child links : a NULL right link points to the inorder successor (and a NULL left link, if threaded, to the inorder predecessor), with a flag bit per link that tells a thread from a child.
Why: The purpose of threading is to use the n + 1 n + 1 n + 1 links that would otherwise be wasted; adding a new pointer field would cost more memory, not less. A tree with parent pointers is a different structure (it can also be traversed without a stack, but it is not a threaded tree). Horowitz, Sahni and Mehta, Fundamentals of Data Structures , and Knuth, The Art of Computer Programming , Vol. 1, §2.3.1, define threads this way.
Key idea
Traversals can be made iterative with an explicit stack (push right before left for preorder; walk left, pop, go right for inorder), or stack-free by threading the n + 1 n + 1 n + 1 NULL links to inorder successors.
TEE Exam note
For “write a non-recursive algorithm for preorder/inorder traversal” give the stack algorithm, then trace it on a small tree showing the stack after each step. For “what is a threaded binary tree?” explain that NULL links are replaced by threads to the inorder successor/predecessor, draw the threads as dotted arrows, show the flag fields, and state the advantage (traversal without stack or recursion).
Common mistake
Pushing the left child before the right child in iterative preorder. The right child would then be popped first, giving node-right-left order.
Common mistake
Following a thread as if it were a child (e.g. when freeing or counting nodes). Code that walks a threaded tree must check the flag before going down a right link.
Key takeaways
Iterative preorder: pop, visit, push right then left (non-NULL only).
Iterative inorder: push the left chain, pop and visit, then go right.
Threads reuse the n + 1 n + 1 n + 1 NULL links to point to inorder successors (and predecessors), with flag bits.
Threaded inorder traversal needs neither recursion nor a stack.
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice In iterative preorder, why is the right child pushed before the left child?
A To visit the right subtree first B So that the left child is on top of the stack and is processed first C Because the right child is always present D It does not matter
Check answer
Show answer Answer: B. So that the left child is on top of the stack and is processed first
A stack returns the last item pushed; pushing left last makes left come out first, giving node-left-right.
Question 2 · multiple choice Iterative inorder is run on the tree with root 1, left child 2 and right child 3. What does the stack hold just before the first pop?
A Nothing B 1 only C 1 and 2 (2 on top) D 1, 2 and 3
Check answer
Show answer Answer: C. 1 and 2 (2 on top)
The algorithm first pushes the left chain 1, 2; the first pop returns 2, which is visited first. 3 is pushed only after 1 is visited.
Question 3 · multiple choice In a right-threaded binary tree, where does the thread of a node with no right child point?
A To its parent B To the root C To its left child D To its inorder successor
Check answer
Show answer Answer: D. To its inorder successor
The thread leads to the node that comes next in inorder. That is sometimes the parent (G → D), but not always (J → A, its grandparent’s parent).
Question 4 · multiple choice What does this program print?
C · q6-stack.c Copy #include <stdio.h>
#include <stddef.h>
typedef struct n {
struct n * l;
int v;
struct n * r;
} N;
int main( void )
{
N d = { NULL , 4 , NULL }, e = { NULL , 5 , NULL }, c = { NULL , 3 , NULL };
N b = { & d, 2 , & e}, a = { & b, 1 , & c};
N * st[ 10 ];
int top = - 1 ;
st[ ++ top] = & a;
while (top >= 0 ) {
N * v = st[top -- ];
printf( "%d " , v->v);
if (v->r) st[ ++ top] = v->r;
if (v->l) st[ ++ top] = v->l;
}
printf( " \n " );
return 0 ;
} A 1 3 2 5 4 B 4 2 5 1 3 C 1 2 4 5 3 D 1 2 3 4 5
Check answer
Show answer Answer: C. 1 2 4 5 3
This is the iterative preorder: 1, then its left subtree (2 4 5), then 3. “1 3 2 5 4” would result from pushing left before right.
Question 5 · multiple choice How many NULL links can a binary tree with 10 nodes turn into threads?
A 9 B 10 C 11 D 20
Check answer
Show answer Answer: C. 11
2 n − ( n − 1 ) = n + 1 = 11 2n - (n - 1) = n + 1 = 11 2 n − ( n − 1 ) = n + 1 = 11 links are NULL and available for threads.
Question 6 · short answer
Write a non-recursive algorithm for inorder traversal using a stack and trace it on the tree with root A, left child B (with left child D) and right child C.
Show worked answer Algorithm: cur = root; while cur ≠ NULL or stack not empty: { while cur ≠ NULL: push cur, cur = cur→left; cur = pop(); visit cur; cur = cur→right }. Trace: push A, push B, push D (stack A B D); D’s left is NULL; pop D, visit D, cur = D→right = NULL; pop B, visit B, cur = NULL; pop A, visit A, cur = C; push C; C’s left is NULL; pop C, visit C, cur = NULL; stack empty: stop. Output: D B A C.