Loading lessons...
Binary Tree Traversals & Threaded Binary Trees
Binary Tree Traversals & Threaded Binary Trees
To print, copy, search or evaluate a tree we must visit every node exactly once in some systematic order. Such an order is called a traversal.
Unlike a list, a tree has no single natural order, so there are several: preorder, inorder, postorder and level order. This lesson gives each one recursively and iteratively, shows how to rebuild a tree from two traversals, and ends with threaded binary trees, which make traversal possible without a stack.
Binary tree traversals
All examples use this tree:
A
/ \
B C
/ \ / \
D E G H
/ / \
F J K
/
L1. The Three Depth-First Traversals
At every node there are three things to do: visit the Node, traverse its Left subtree, traverse its Right subtree. The order of these three steps gives the name.
| Traversal | Order | Result for the example tree |
|---|---|---|
| Preorder | N L R (root first) | A B D E F C G H J L K |
| Inorder | L N R (root in the middle) | D B F E A G C L J H K |
| Postorder | L R N (root last) | D F E B G L J K H C A |
Preorder (NLR)
Algorithm PREORDER(T)
if T ≠ NULL then
VISIT(T) // 1. node
PREORDER(LEFT[T]) // 2. left subtree
PREORDER(RIGHT[T]) // 3. right subtreeInorder (LNR)
Algorithm INORDER(T)
if T ≠ NULL then
INORDER(LEFT[T]) // 1. left subtree
VISIT(T) // 2. node
INORDER(RIGHT[T]) // 3. right subtreePostorder (LRN)
Algorithm POSTORDER(T)
if T ≠ NULL then
POSTORDER(LEFT[T]) // 1. left subtree
POSTORDER(RIGHT[T]) // 2. right subtree
VISIT(T) // 3. nodeHow to get the answer quickly by hand
- Preorder: walk around the outside of the tree starting left of the root; write a node the first time you pass it (on its left side).
- Inorder: write a node when you pass underneath it. It is the tree "squashed flat" onto a line.
- Postorder: write a node the last time you pass it (on its right side).
Uses of each traversal
| Traversal | Typical use |
|---|---|
| Preorder | Copying a tree; printing a folder structure; prefix form of an expression tree |
| Inorder | Printing a binary search tree in sorted order; infix form of an expression |
| Postorder | Deleting a tree (children before parent); evaluating an expression tree; computing folder sizes |
| Level order | Printing level by level; shortest path in unweighted trees; checking completeness |
Complexity: every node is visited once
- O(n) time. The recursion uses O(h) stack space, where h is the height (O(log n) for a balanced tree, O(n) for a skewed one).
2. Iterative Traversals with an Explicit Stack
Recursion uses the system stack; we can use our own stack instead.
Iterative preorder
Algorithm PREORDER_ITER(ROOT)
if ROOT = NULL then return
PUSH(ROOT)
while stack not empty do
PTR ← POP()
VISIT(PTR)
if RIGHT[PTR] ≠ NULL then PUSH(RIGHT[PTR]) // right first ...
if LEFT[PTR] ≠ NULL then PUSH(LEFT[PTR]) // ... so left pops firstIterative inorder
Algorithm INORDER_ITER(ROOT)
PTR ← ROOT
while PTR ≠ NULL or stack not empty do
while PTR ≠ NULL do // go as far left as possible
PUSH(PTR)
PTR ← LEFT[PTR]
PTR ← POP() // leftmost unvisited node
VISIT(PTR)
PTR ← RIGHT[PTR] // then its right subtreeTrace of INORDER_ITER on the subtree rooted at B (B, D, E, F):
| Step | Action | Stack | Output |
|---|---|---|---|
| 1 | push B, push D (go left) | B D | |
| 2 | pop D, visit; D has no right | B | D |
| 3 | pop B, visit; move to E | D B | |
| 4 | push E, push F | E F | D B |
| 5 | pop F, visit | E | D B F |
| 6 | pop E, visit | D B F E |
Iterative postorder (two stacks)
Push nodes in the order N R L (a mirrored preorder) onto a second stack; popping the second stack then gives L R N.
Algorithm POSTORDER_ITER(ROOT)
PUSH1(ROOT)
while stack1 not empty do
PTR ← POP1()
PUSH2(PTR)
if LEFT[PTR] ≠ NULL then PUSH1(LEFT[PTR])
if RIGHT[PTR] ≠ NULL then PUSH1(RIGHT[PTR])
while stack2 not empty do
VISIT(POP2())3. Level-Order (Breadth-First) Traversal
Visit the nodes level by level, left to right, using a queue.
Algorithm LEVEL_ORDER(ROOT)
if ROOT = NULL then return
ENQUEUE(ROOT)
while queue not empty do
PTR ← DEQUEUE()
VISIT(PTR)
if LEFT[PTR] ≠ NULL then ENQUEUE(LEFT[PTR])
if RIGHT[PTR] ≠ NULL then ENQUEUE(RIGHT[PTR])Result for the example tree: A B C D E G H F J K L.
| Dequeued | Queue after enqueuing its children |
|---|---|
| A | B C |
| B | C D E |
| C | D E G H |
| D | E G H |
| E | G H F |
| G | H F |
| H | F J K |
| F | J K |
| J | K L |
| K | L |
| L | (empty) |
4. Reconstructing a Binary Tree from Two Traversals
A binary tree is uniquely determined by:
- inorder + preorder, or
- inorder + postorder.
Preorder + postorder alone is not enough (it cannot tell a single left child from a single right child). Inorder is always needed because it separates the left subtree from the right.
Method (inorder + preorder)
- The first element of the preorder is the root.
- Find the root in the inorder: everything to its left is the left subtree, everything to its right is the right subtree.
- Repeat for each subtree, using the next elements of the preorder as subtree roots.
Example. Preorder: A B D E F C G H J L K. Inorder: D B F E A G C L J H K.
| Step | Root (from preorder) | Left subtree (inorder) | Right subtree (inorder) |
|---|---|---|---|
| 1 | A | D B F E | G C L J H K |
| 2 | B | D | F E |
| 3 | D | leaf | |
| 4 | E | F | - |
| 5 | F | leaf | |
| 6 | C | G | L J H K |
| 7 | G | leaf | |
| 8 | H | L J | K |
| 9 | J | L | - |
| 10 | L, K | leaves |
The result is exactly the example tree.
Method (inorder + postorder)
Same idea, but the root is the last element of the postorder, and subtree roots are taken from the end backwards.
Example. Inorder: D B F E A G C L J H K. Postorder: D F E B G L J K H C A.
- Last of postorder is A → root. Left part inorder
D B F Ehas postorderD F E B→ root B; right partG C L J H Khas postorderG L J K H C→ root C. - Continuing in the same way gives the same tree again.
Reconstruction in C
/* pre[] and in[] hold the traversals; *p is the next index in pre[] */
struct TreeNode *build(char pre[], char in[], int lo, int hi, int *p) {
if (lo > hi) return NULL;
struct TreeNode *t = newNode(pre[(*p)++]); /* next preorder item is the root */
int k = lo;
while (in[k] != t->data) k++; /* find it in the inorder */
t->left = build(pre, in, lo, k - 1, p);
t->right = build(pre, in, k + 1, hi, p);
return t;
}5. Threaded Binary Trees
A linked binary tree with n nodes has n + 1 NULL links - more than half of all links are wasted. Also, an inorder traversal needs a stack (or recursion) to climb back up the tree.
A threaded binary tree (Perlis and Thornton) replaces the NULL links with threads:
- a NULL right link points to the node's inorder successor;
- a NULL left link points to the node's inorder predecessor.
Each node gets two one-bit flags, LTHREAD and RTHREAD, telling whether the link is a real child pointer or a thread. A header node is used so that the first node's predecessor thread and the last node's successor thread have somewhere to point.
struct ThreadNode {
struct ThreadNode *left, *right;
int data;
int lthread, rthread; /* 1 = link is a thread, 0 = link is a child */
};For the example tree (inorder D B F E A G C L J H K), the threads of a two-way threaded tree are:
| Node | Left link | Right link |
|---|---|---|
| D | thread → header (no predecessor) | thread → B |
| B | child D | child E |
| F | thread → B | thread → E |
| E | child F | thread → A |
| A | child B | child C |
| G | thread → A | thread → C |
| C | child G | child H |
| L | thread → C | thread → J |
| J | child L | thread → H |
| H | child J | child K |
| K | thread → H | thread → header (no successor) |
Every link that would have been NULL now points to the inorder neighbour.
| Kind | Threads used |
|---|---|
| One-way (right) threaded | Only NULL right links become successor threads |
| Two-way threaded | Both NULL left (predecessor) and NULL right (successor) links are threads |
Inorder traversal without a stack
Algorithm INSUCC(P)
// Inorder successor of node P in a threaded tree
Q ← RIGHT[P]
if RTHREAD[P] = 0 then // real right child: go to its leftmost node
while LTHREAD[Q] = 0 do
Q ← LEFT[Q]
return QHow it works: if P's right link is a thread, it already points to the successor. Otherwise the successor is the leftmost node of P's right subtree. No stack and no recursion are needed.
| Advantages | Disadvantages |
|---|---|
| Inorder traversal in O(n) with O(1) extra space | Two extra flag fields per node |
| Inorder successor/predecessor found quickly | Insertion and deletion must update threads - more complex |
| No NULL links are wasted | Harder to understand and debug |
Key points to remember - Preorder NLR, inorder LNR, postorder LRN; level order uses a queue. - Example tree: pre A B D E F C G H J L K; in D B F E A G C L J H K; post D F E B G L J K H C A; level A B C D E G H F J K L. - All traversals are O(n) time; recursion uses O(h) stack. - A unique tree needs inorder + (preorder or postorder). - Threaded trees replace NULL links with inorder predecessor/successor threads → stackless inorder traversal.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. Explain preorder, inorder and postorder traversals with recursive algorithms. Give all three for a given tree. (7.5 Marks)
- Write: the NLR/LNR/LRN definitions, the three algorithms, and the outputs for the example tree.
- Q2. Write a non-recursive algorithm for inorder traversal using a stack. (5 Marks)
- Write:
INORDER_ITERand a short trace table. - Q3. Construct the binary tree from preorder A B D E F C G H J L K and inorder D B F E A G C L J H K. Also give its postorder. (7.5 Marks)
- Write: the step table, the final tree, postorder D F E B G L J K H C A.
- Q4. What is a threaded binary tree? Explain how inorder traversal is done without a stack. (5 Marks)
- Write: the wasted n + 1 NULL links, threads to inorder successor/predecessor, LTHREAD/RTHREAD flags, header node,
INSUCC.