Threaded binary tree
Point each empty right link of the tree at the node's inorder successor (a thread); then an inorder walk needs no stack and no recursion.
A binary tree with n nodes has n + 1 null links. Perlis and Thornton proposed putting them to use: each empty right
link points at the node's inorder successor. These links are called threads. (The full version also points
empty left links at the inorder predecessor.)
- Time:
Θ(n) - Space:
O(1) extra for the walk - Horowitz–Sahni, chapter 5
A seven-node search tree; three threads are drawn (3→6, 7→15 and 17→18) and the walk gives 3 6 7 15 17 18 20 without a stack.
class Node:def __init__(self, key):self.key = keyself.left = Noneself.right = Noneself.thread = None # used only when right is empty: the inorder successordef threaded(root):# Phase 1: an inorder walk; every node with an empty right link gets a thread to its successor.stack = []prev = Nonenode = rootwhile node is not None or stack:if node is not None:stack.append(node)node = node.leftelse:node = stack.pop()if prev is not None and prev.right is None:prev.thread = nodeprev = nodenode = node.right# Phase 2: inorder again, with no stack: follow a thread, or go right and then all the way left.out = []node = rootwhile node is not None and node.left is not None:node = node.leftwhile node is not None:out.append(node.key)if node.right is None:node = node.threadelse:node = node.rightwhile node.left is not None:node = node.leftreturn out
Start
Local variables
Orange = changed in this step
root object
- key = 15
- left = Node(key=6, left=Node(key=3, left=None, right=None, thread=None), right=Node(key=7, left=None, right=None, thread=None), thread=None)
- right = Node(key=18, left=Node(key=17, left=None, right=None, thread=None), right=Node(key=20, left=None, right=None, thread=None), thread=None)
- thread = None
Call stack
- threaded()line 9
Explanation
The idea
A binary tree with n nodes has n + 1 null links. Perlis and Thornton proposed putting them to use: each empty right
link points at the node's inorder successor. These links are called threads. (The full version also points
empty left links at the inorder predecessor.)
A walk without a stack
With threads, the next inorder node is easy to find from any node:
- if it has a right child: one step right, then as far left as possible;
- otherwise: follow its thread.
So the inorder walk runs without a stack and without recursion.
In practice
We need to know whether a right link is a real child or a thread. Textbooks keep a flag bit in each node for that; here
the thread lives in a separate field, thread. Threads are drawn dashed.