Lesson 19 +35 XP

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 traversalsBinary tree traversals

All examples use this tree:

DIAGRAM
                 A
              /     \
             B       C
            / \     / \
           D   E   G   H
              /       / \
             F       J   K
                    /
                   L

1. 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.

TraversalOrderResult for the example tree
PreorderN L R (root first)A B D E F C G H J L K
InorderL N R (root in the middle)D B F E A G C L J H K
PostorderL R N (root last)D F E B G L J K H C A

Preorder (NLR)

PSEUDO
Algorithm PREORDER(T)
if T ≠ NULL then
    VISIT(T)                    // 1. node
    PREORDER(LEFT[T])           // 2. left subtree
    PREORDER(RIGHT[T])          // 3. right subtree

Inorder (LNR)

PSEUDO
Algorithm INORDER(T)
if T ≠ NULL then
    INORDER(LEFT[T])            // 1. left subtree
    VISIT(T)                    // 2. node
    INORDER(RIGHT[T])           // 3. right subtree

Postorder (LRN)

Algorithm POSTORDER(T)
if T ≠ NULL then
    POSTORDER(LEFT[T])          // 1. left subtree
    POSTORDER(RIGHT[T])         // 2. right subtree
    VISIT(T)                    // 3. node

How 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

TraversalTypical use
PreorderCopying a tree; printing a folder structure; prefix form of an expression tree
InorderPrinting a binary search tree in sorted order; infix form of an expression
PostorderDeleting a tree (children before parent); evaluating an expression tree; computing folder sizes
Level orderPrinting 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

PSEUDO
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 first

Iterative inorder

PSEUDO
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 subtree

Trace of INORDER_ITER on the subtree rooted at B (B, D, E, F):

StepActionStackOutput
1push B, push D (go left)B D
2pop D, visit; D has no rightBD
3pop B, visit; move to ED B
4push E, push FE FD B
5pop F, visitED B F
6pop E, visitD 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.

PSEUDO
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.

PSEUDO
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.

DequeuedQueue after enqueuing its children
AB C
BC D E
CD E G H
DE G H
EG H F
GH F
HF J K
FJ K
JK L
KL
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)

  1. The first element of the preorder is the root.
  2. Find the root in the inorder: everything to its left is the left subtree, everything to its right is the right subtree.
  3. 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.

StepRoot (from preorder)Left subtree (inorder)Right subtree (inorder)
1AD B F EG C L J H K
2BDF E
3Dleaf
4EF-
5Fleaf
6CGL J H K
7Gleaf
8HL JK
9JL-
10L, Kleaves

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 E has postorder D F E B → root B; right part G C L J H K has postorder G L J K H C → root C.
  • Continuing in the same way gives the same tree again.

Reconstruction in C

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.

C
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:

NodeLeft linkRight link
Dthread → header (no predecessor)thread → B
Bchild Dchild E
Fthread → Bthread → E
Echild Fthread → A
Achild Bchild C
Gthread → Athread → C
Cchild Gchild H
Lthread → Cthread → J
Jchild Lthread → H
Hchild Jchild K
Kthread → Hthread → header (no successor)

Every link that would have been NULL now points to the inorder neighbour.

KindThreads used
One-way (right) threadedOnly NULL right links become successor threads
Two-way threadedBoth 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 Q

How 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.

AdvantagesDisadvantages
Inorder traversal in O(n) with O(1) extra spaceTwo extra flag fields per node
Inorder successor/predecessor found quicklyInsertion and deletion must update threads - more complex
No NULL links are wastedHarder to understand and debug
💡 Tip

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.

🎯 END-TERM EXAM PREP

📝 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_ITER and 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.