Binary Trees and Binary Search Trees: Traversals and O(h)
Trees model anything hierarchical: folders, the structure of an HTML page, the parse of an arithmetic expression. Binary search trees add an ordering rule that turns the tree into a search structure. Their running time depends on one number, the height, and most of what there is to know about them follows from that. Examples use Python 3.10 or later and only the standard library.
Tree vocabulary
- A tree is a set of nodes connected so that there is exactly one path between any two. One node is the root.
- Each node except the root has one parent; the nodes directly below a node are its children. A node with no children is a leaf.
- The depth of a node is the number of edges from the root down to it (the root has depth 0). The height of a tree is the largest depth of any node, the number of edges on its longest root-to-leaf path. (Some books count nodes instead of edges; the difference is 1, so check which convention a source uses.)
- A subtree is a node together with everything below it.
In a binary tree every node has at most two children, called left and right. A binary tree of height h holds at most 2^(h+1) - 1 nodes, so a tree with n nodes has height at least about log2 n. It can be as tall as n - 1 if every node has only one child.
The four traversals
A traversal visits every node once. The three depth-first orders differ only in when the node itself is visited relative to its two subtrees, and they are naturally recursive (see recursion explained). The fourth, level order, visits the tree one depth at a time using a queue.
- Preorder: node, left subtree, right subtree. Useful for copying a tree or printing it as an outline.
- Inorder: left subtree, node, right subtree. On a binary search tree it visits the keys in sorted order.
- Postorder: left subtree, right subtree, node. Children are finished before their parent, which suits deleting a tree or evaluating an expression tree.
- Level order: all nodes at depth 0, then depth 1, and so on. This is breadth-first search on a tree.
from collections import deque
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# F
# / \
# B G
# / \ \
# A D I
# / \ /
# C E H
root = Node("F",
Node("B", Node("A"), Node("D", Node("C"), Node("E"))),
Node("G", None, Node("I", Node("H"))))
def preorder(node, out): # node, then left, then right
if node:
out.append(node.value)
preorder(node.left, out)
preorder(node.right, out)
return out
def inorder(node, out): # left, then node, then right
if node:
inorder(node.left, out)
out.append(node.value)
inorder(node.right, out)
return out
def postorder(node, out): # left, then right, then node
if node:
postorder(node.left, out)
postorder(node.right, out)
out.append(node.value)
return out
def level_order(node): # breadth first, with a queue
out, queue = [], deque([node])
while queue:
n = queue.popleft()
out.append(n.value)
for child in (n.left, n.right):
if child:
queue.append(child)
return out
def height(node): # edges on the longest root-to-leaf path
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
print("preorder ", " ".join(preorder(root, [])))
print("inorder ", " ".join(inorder(root, [])))
print("postorder ", " ".join(postorder(root, [])))
print("level order", " ".join(level_order(root)))
print("height", height(root))
preorder F B A D C E G I H
inorder A B C D E F G H I
postorder A C E D B H I G F
level order F B G A D I C E H
height 3
Each traversal does constant work per node, so all four run in O(n) time. The recursive ones use stack space proportional to the height, O(h); level order holds up to one full level in its queue, which can be about n/2 nodes in a complete tree.
The binary search tree property
A binary search tree (BST) is a binary tree in which, for every node, all keys in its left subtree are smaller than its key and all keys in its right subtree are larger. The rule applies to whole subtrees, not just to the immediate children, which is a common mistake when writing a "is this a valid BST?" check. The tree in the traversal example happens to be a BST over the letters, which is why its inorder traversal came out as A to I.
To search, start at the root: if the key is smaller, go left; if larger, go right; stop when you find it or fall off the tree. To insert, search for the key and attach a new leaf where the search fell off. Each step goes down one level, so both take O(h) time, where h is the height. Deletion is also O(h); its tricky case, a node with two children, replaces the node's key with its inorder successor (the smallest key in its right subtree) and then deletes that successor, which has at most one child.
Why the height is everything
O(h) is only as good as h. If keys arrive in random order, the expected height is O(log n). If they arrive already sorted, every new key is larger than everything in the tree and becomes the right child of the previous one: the tree is a chain, h = n - 1, and search degrades to O(n), no better than scanning a list.
import random
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(root, key): # O(h), iterative
new = Node(key)
if root is None:
return new
node = root
while True:
if key < node.key:
if node.left is None:
node.left = new
return root
node = node.left
elif key > node.key:
if node.right is None:
node.right = new
return root
node = node.right
else:
return root # key already present: ignore it
def search(root, key): # O(h): one comparison per level
node = root
while node is not None and node.key != key:
node = node.left if key < node.key else node.right
return node is not None
def height(root): # iterative, so a long chain cannot hit the recursion limit
best, stack = -1, [(root, 0)]
while stack:
node, depth = stack.pop()
if node:
best = max(best, depth)
stack.append((node.left, depth + 1))
stack.append((node.right, depth + 1))
return best
root = None
for k in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, k)
print(search(root, 60), search(root, 65), "height", height(root))
n = 1000
chain = None
for k in range(n): # keys arrive already sorted
chain = insert(chain, k)
keys = list(range(n))
random.seed(1)
random.shuffle(keys)
shuffled = None
for k in keys: # same keys, random order
shuffled = insert(shuffled, k)
print("sorted inserts: height", height(chain))
print("random inserts: height", height(shuffled))
True False height 2
sorted inserts: height 999
random inserts: height 19
The seven balanced inserts give height 2. A thousand sorted inserts give height 999, so a search for the largest key walks all 1,000 nodes, and building the tree took about n^2/2 steps in total. The same thousand keys in one shuffled order (with random.seed(1)) gave height 19 on this run: not the minimum of 9 that a perfectly balanced tree would have, but logarithmic in shape. The height function here is iterative on purpose; a recursive one would hit Python's default recursion limit of 1000 on the chain.
Balanced trees
You usually cannot choose the order in which keys arrive, so a plain BST gives no worst-case guarantee. Self-balancing trees fix that. After each insert or delete they check a balance condition and, where it is broken, restore it with rotations: small local rearrangements of a few nodes that change the shape of the tree while keeping the BST ordering intact. Each rotation is O(1), and only nodes along the path from the change to the root are affected.
- An AVL tree, named after Adelson-Velsky and Landis, requires that at every node the heights of the two subtrees differ by at most 1.
- A red-black tree colors each node red or black and enforces rules on those colors that keep the longest root-to-leaf path at most twice the shortest.
Both keep the height at O(log n), so search, insert and delete are O(log n) in the worst case. AVL trees are more strictly balanced; red-black trees tend to do fewer rotations on updates. The details of each rotation case are long and well covered in textbooks such as "Introduction to Algorithms" by Cormen, Leiserson, Rivest and Stein.
What to use in Python
Python's standard library has no balanced binary search tree. Most of the time you do not need one:
- For lookup by key with no ordering, a
dictorsetis O(1) on average. - For sorted data that changes rarely, a sorted list with the
bisectmodule finds a key or a position in O(log n). Inserting withbisect.insortstill shifts items, O(n), so this suits read-heavy work. See binary search. - For repeatedly taking the smallest item, a heap is simpler and faster than a tree; see heaps and priority queues.
| Operation | BST, balanced | BST, unbalanced worst case | Sorted list + bisect |
|---|---|---|---|
| Search | O(log n) | O(n) | O(log n) |
| Insert or delete | O(log n) | O(n) | O(n) (shifting) |
| All keys in order | O(n) | O(n) | O(n) |
| Minimum | O(log n) | O(n) | O(1) |
Check yourself
- A tree has a root 10 with left child 5 and right child 15, and 5 has a right child 12. Is it a BST? (No: 12 is in the left subtree of 10 but larger than 10.)
- Which traversal of a BST prints its keys in sorted order? (Inorder.)
- You insert the keys 1 to n in increasing order into a plain BST. What is the height, and the cost of searching for n? (n - 1; O(n).)