Lesson 16 · Non-linear structures

Threaded Binary Trees

A binary tree with n nodes has n + 1 empty links. A threaded binary tree points each one at an in-order neighbour, so traversal needs no stack and no recursion.

Threaded Binary Trees concept diagramTwo copies of a five-node binary tree. The left copy shows six null links marked as wasted. The right copy replaces them with dashed threads to each node's in-order predecessor and successor.ordinary binary tree5 nodes, 10 links, 6 of them nullthreaded binary treethe same 6 links, now pointing somewhere useful∅∅∅∅∅∅∅∅AABBCCDDEEDBEACin-orderto successorto predecessor
1

Threads in Place of Null Links

  1. key – the value stored in the node.
  2. left – a child, or a thread to the in-order predecessor.
  3. right – a child, or a thread to the in-order successor.
  4. lthread – 1 if left is a thread, 0 if it is a child.
  5. rthread – 1 if right is a thread, 0 if it is a child.

A threaded binary tree is a binary tree in which every null child pointer is replaced by a pointer to the node's in-order predecessor (for a null left link) or in-order successor (for a null right link). Those replacement pointers are called threads.

The motivation is waste. A tree with n nodes has 2n link fields, but only n − 1 of them hold children, because every node except the root has exactly one parent. That leaves n + 1 links holding null. A threaded binary tree turns that dead memory into a map of the in-order sequence.

With the threads in place, in-order traversal needs no stack and no recursion. The idea is due to Perlis and Thornton (1960).

  • The flag bits are required: a pointer alone cannot say whether it is a child or a thread
  • The first node has no predecessor and the last has no successor, so those two links stay null (or point to a header node)
2

Single vs Double Threading

A single threaded binary tree threads only one side. The common form is right-threaded: every null right link points to the in-order successor, and null left links stay null. That is enough for a forward in-order traversal.

A double threaded binary tree (fully threaded) threads both sides. Null left links point to the predecessor and null right links point to the successor, so the tree can be walked forwards and backwards with equal ease.

Many textbook implementations add a header (dummy) node. The leftmost node's left thread and the rightmost node's right thread point to the header instead of null, and the real root hangs off the header's left link. That removes the two special cases at the ends of the sequence.

The three variants compared
VariantNull left linkNull right linkCheap operations
Right-threaded (single)stays nullthread to successorforward in-order, successor
Left-threaded (single)thread to predecessorstays nullreverse in-order, predecessor
Double threadedthread to predecessorthread to successorboth directions, both neighbours
  • Single threading needs one flag per node; double threading needs two
  • Pick single threading when the program only ever walks forwards
3

Inorder Traversal With No Stack

  1. Start – from the root, follow left children while lthread is 0. The node reached is the first in order.
  2. Visit – output the current node.
  3. Thread? – if rthread is 1, move to right and repeat from Visit.
  4. Child? – otherwise move to right, then follow left children while lthread is 0, and repeat from Visit.
  5. Stop – when the pointer is null (or the header node).

In an ordinary binary tree, in-order traversal needs a stack (explicit or the call stack) because after finishing a left subtree there is no pointer back up to the parent. In a threaded tree that pointer already exists: it is the right thread of the last node visited.

The algorithm has only two moves. To find a node's successor, check its right flag. If it is a thread, follow it. If it is a child, go right once and then as far left as possible.

Each link is crossed at most twice, once going down a child link and once along a thread, so the traversal is O(n) time and O(1) extra space. The recursive version costs O(h) stack space, which is O(n) for a skewed tree.

  • No stack, no recursion, no parent pointers
  • Reverse in-order is the mirror: start at the rightmost node and follow left threads
Key reference

Terms, operations, and practical uses

Core vocabulary

  • ThreadA former null link that now points to the node's in-order predecessor (left) or successor (right).
  • lthread / rthreadOne bit per side: 1 means the link is a thread, 0 means it is a real child.
  • Header nodeA dummy node that the two end threads point to, so no traversal ever meets null.
  • Leftmost nodeReached by following left children while lthread is 0; the first node in order.

Costs

  • In-order traversalO(n) time, O(1) extra space: each link is crossed at most twice.
  • InsertO(h) search plus O(1) rewiring of the parent and the new leaf.
  • Successor of a leafO(1): the right thread names it.
  • Recursive traversalO(h) call-stack frames, O(n) on a skewed tree; threads remove them.

Related lessons

  • Binary TreesThe node-and-link structure threading builds on.
  • Tree TraversalsThe recursive and stack-based in-order walks threads replace.
  • Binary Search TreesThe search rule threaded insertion reuses unchanged.
  • StacksThe auxiliary memory an ordinary in-order traversal needs.
Implementation

Code in Python, C++ and Java

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        # True means the link is a thread to an in-order neighbour,
        # False means it is a real child.
        self.lthread = True
        self.rthread = True


def insert(root, key):
    node = Node(key)
    if root is None:
        return node
    cur = root
    while True:
        if key == cur.key:
            return root
        if key < cur.key:
            if cur.lthread:
                node.left = cur.left  # inherit the parent's predecessor
                node.right = cur  # the parent is the successor
                cur.left = node
                cur.lthread = False
                return root
            cur = cur.left
        else:
            if cur.rthread:
                node.right = cur.right  # inherit the parent's successor
                node.left = cur  # the parent is the predecessor
                cur.right = node
                cur.rthread = False
                return root
            cur = cur.right


def leftmost(node):
    while node is not None and not node.lthread:
        node = node.left
    return node


def rightmost(node):
    while node is not None and not node.rthread:
        node = node.right
    return node


def successor(node):
    if node.rthread:
        return node.right
    return leftmost(node.right)


def predecessor(node):
    if node.lthread:
        return node.left
    return rightmost(node.left)


def inorder(root):
    out = []
    cur = leftmost(root)
    while cur is not None:
        out.append(cur.key)
        cur = successor(cur)
    return out


def reverse_inorder(root):
    out = []
    cur = rightmost(root)
    while cur is not None:
        out.append(cur.key)
        cur = predecessor(cur)
    return out


def find(root, key):
    cur = root
    while cur is not None:
        if key == cur.key:
            return cur
        if key < cur.key:
            cur = None if cur.lthread else cur.left
        else:
            cur = None if cur.rthread else cur.right
    return None


root = None
for key in [20, 10, 30, 5, 15, 25]:
    root = insert(root, key)
print("In-order:", *inorder(root))

root = insert(root, 17)
print("After inserting 17:", *inorder(root))
print("Reverse in-order:", *reverse_inorder(root))
print("Successor of 17:", successor(find(root, 17)).key)
print("Predecessor of 17:", predecessor(find(root, 17)).key)
#include <iostream>
#include <vector>

struct Node {
    int key;
    Node* left = nullptr;
    Node* right = nullptr;
    // true means the link is a thread to an in-order neighbour,
    // false means it is a real child.
    bool lthread = true;
    bool rthread = true;
    explicit Node(int k) : key(k) {}
};

Node* insert(Node* root, int key) {
    if (root == nullptr) return new Node(key);
    Node* cur = root;
    while (true) {
        if (key == cur->key) return root;
        if (key < cur->key) {
            if (cur->lthread) {
                Node* node = new Node(key);
                node->left = cur->left;  // inherit the parent's predecessor
                node->right = cur;       // the parent is the successor
                cur->left = node;
                cur->lthread = false;
                return root;
            }
            cur = cur->left;
        } else {
            if (cur->rthread) {
                Node* node = new Node(key);
                node->right = cur->right;  // inherit the parent's successor
                node->left = cur;          // the parent is the predecessor
                cur->right = node;
                cur->rthread = false;
                return root;
            }
            cur = cur->right;
        }
    }
}

Node* leftmost(Node* node) {
    while (node != nullptr && !node->lthread) node = node->left;
    return node;
}

Node* rightmost(Node* node) {
    while (node != nullptr && !node->rthread) node = node->right;
    return node;
}

Node* successor(Node* node) {
    return node->rthread ? node->right : leftmost(node->right);
}

Node* predecessor(Node* node) {
    return node->lthread ? node->left : rightmost(node->left);
}

std::vector<int> inorder(Node* root) {
    std::vector<int> out;
    for (Node* cur = leftmost(root); cur != nullptr; cur = successor(cur)) {
        out.push_back(cur->key);
    }
    return out;
}

std::vector<int> reverseInorder(Node* root) {
    std::vector<int> out;
    for (Node* cur = rightmost(root); cur != nullptr; cur = predecessor(cur)) {
        out.push_back(cur->key);
    }
    return out;
}

Node* find(Node* root, int key) {
    Node* cur = root;
    while (cur != nullptr && cur->key != key) {
        if (key < cur->key) {
            cur = cur->lthread ? nullptr : cur->left;
        } else {
            cur = cur->rthread ? nullptr : cur->right;
        }
    }
    return cur;
}

void print(const char* label, const std::vector<int>& keys) {
    std::cout << label;
    for (int k : keys) std::cout << ' ' << k;
    std::cout << '\n';
}

int main() {
    Node* root = nullptr;
    for (int key : {20, 10, 30, 5, 15, 25}) root = insert(root, key);
    print("In-order:", inorder(root));

    root = insert(root, 17);
    print("After inserting 17:", inorder(root));
    print("Reverse in-order:", reverseInorder(root));
    std::cout << "Successor of 17: " << successor(find(root, 17))->key << '\n';
    std::cout << "Predecessor of 17: " << predecessor(find(root, 17))->key << '\n';
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static class Node {
        int key;
        Node left, right;
        // true means the link is a thread to an in-order neighbour,
        // false means it is a real child.
        boolean lthread = true, rthread = true;

        Node(int key) {
            this.key = key;
        }
    }

    static Node insert(Node root, int key) {
        if (root == null) return new Node(key);
        Node cur = root;
        while (true) {
            if (key == cur.key) return root;
            if (key < cur.key) {
                if (cur.lthread) {
                    Node node = new Node(key);
                    node.left = cur.left; // inherit the parent's predecessor
                    node.right = cur; // the parent is the successor
                    cur.left = node;
                    cur.lthread = false;
                    return root;
                }
                cur = cur.left;
            } else {
                if (cur.rthread) {
                    Node node = new Node(key);
                    node.right = cur.right; // inherit the parent's successor
                    node.left = cur; // the parent is the predecessor
                    cur.right = node;
                    cur.rthread = false;
                    return root;
                }
                cur = cur.right;
            }
        }
    }

    static Node leftmost(Node node) {
        while (node != null && !node.lthread) node = node.left;
        return node;
    }

    static Node rightmost(Node node) {
        while (node != null && !node.rthread) node = node.right;
        return node;
    }

    static Node successor(Node node) {
        return node.rthread ? node.right : leftmost(node.right);
    }

    static Node predecessor(Node node) {
        return node.lthread ? node.left : rightmost(node.left);
    }

    static List<Integer> inorder(Node root) {
        List<Integer> out = new ArrayList<>();
        for (Node cur = leftmost(root); cur != null; cur = successor(cur)) out.add(cur.key);
        return out;
    }

    static List<Integer> reverseInorder(Node root) {
        List<Integer> out = new ArrayList<>();
        for (Node cur = rightmost(root); cur != null; cur = predecessor(cur)) out.add(cur.key);
        return out;
    }

    static Node find(Node root, int key) {
        Node cur = root;
        while (cur != null && cur.key != key) {
            if (key < cur.key) cur = cur.lthread ? null : cur.left;
            else cur = cur.rthread ? null : cur.right;
        }
        return cur;
    }

    static String join(List<Integer> keys) {
        StringBuilder sb = new StringBuilder();
        for (int k : keys) sb.append(' ').append(k);
        return sb.toString();
    }

    public static void main(String[] args) {
        Node root = null;
        for (int key : new int[] {20, 10, 30, 5, 15, 25}) root = insert(root, key);
        System.out.println("In-order:" + join(inorder(root)));

        root = insert(root, 17);
        System.out.println("After inserting 17:" + join(inorder(root)));
        System.out.println("Reverse in-order:" + join(reverseInorder(root)));
        System.out.println("Successor of 17: " + successor(find(root, 17)).key);
        System.out.println("Predecessor of 17: " + predecessor(find(root, 17)).key);
    }
}
Watch it run

Step through it

Running on insert 20, 10, 30, 5, 15, 25; traverse; insert 17

∅∅20105153025no current nodeLleftkeyrightRflag 1 = thread, 0 = childextra memory usedno stack, no recursionchild linkthread to successorthread to predecessorin-order output
Step 1

Six keys, twelve links, seven of them threads

Inserting 20, 10, 30, 5, 15, 25 gives a BST with 6 nodes and 12 link fields. Only 5 are child links; the other 7 would be null in a plain tree. Here each one points to an in-order neighbour instead: green to the successor, grey to the predecessor. Only 5.left and 30.right stay empty, because nothing comes before 5 or after 30.

Output
1 / 17
4

Inserting a Node

  1. Search – compare with the current key and move left or right while the flag in that direction is 0.
  2. Left insert – new.left = parent.left, new.right = parent, then parent.left = new and parent.lthread = 0.
  3. Right insert – new.right = parent.right, new.left = parent, then parent.right = new and parent.rthread = 0.
  4. Flags – both of the new node's flags are 1, because a new leaf has no children.

Insertion searches exactly like a plain BST, using the flags to decide when the search has run out of children. When the next link in the search direction is a thread, the new node belongs there.

The new node is always a leaf, so both of its links are threads. Its parent is one of its in-order neighbours, and the other neighbour is whatever the parent's thread pointed to before. That is why the new node inherits the parent's thread before the parent's link is overwritten.

Only two nodes change: the parent (one pointer, one flag) and the new node. The cost is O(h) for the search and O(1) for the rewiring, the same as an ordinary BST.

  • Empty tree: the new node becomes the root, and both its threads are null (or point to the header)
  • Deletion is harder: removing a node must repair every thread that pointed to it
5

Finding the Inorder Successor and Predecessor

In a plain binary tree the successor of a node with no right child is found by climbing parents until you arrive from a left child. That needs parent pointers or a fresh search from the root.

In a threaded tree the successor comes straight from the right link: a thread names it directly, and a child means the leftmost node of the right subtree. The predecessor rule is the mirror image, using the left link, and it is only O(1) in a double threaded tree.

Where each neighbour comes from
QueryFlag is 1 (thread)Flag is 0 (child)
Successornode.rightleftmost node of node.right
Predecessornode.leftrightmost node of node.left
  • A leaf answers in O(1); an internal node needs an O(h) walk down
  • Over a full traversal the walks add up to O(n), not O(n·h)
6

Advantages and Disadvantages

The benefit is traversal: in-order walks, successor and predecessor queries become cheap and need no auxiliary memory. That matters when memory is tight or when a program repeatedly steps to the next key from an arbitrary node.

The cost is complexity. Every insertion and deletion must maintain the threads, the flags take space in every node, and code that forgets to check a flag follows a thread as if it were a child and loops. Balanced trees with parent pointers solve most of the same problems, which is why threaded trees are more common in exams and in memory-constrained systems than in standard libraries.

  • Threads only encode in-order; pre-order and post-order still need a stack
  • Morris traversal gets the same O(1) space on a plain tree by adding threads for the walk and removing them after