← back to algorithms

Trees

Nievergelt & Hinrichs · Ch. 5 · Algorithms and Data Structures

A binary search tree keeps keys ordered: left child < parent < right child. Unbalanced, it degrades to a linked list. AVL trees restore balance after every insertion. B-trees generalize to disk-friendly multi-way branching.

20 +1 10 +1 30 0 5 +1 15 0 25 0 35 0 3 0 AVL tree: balance factor = height(left) - height(right), always in -1..+1

Binary search tree

Insert, search, and delete all follow the same path from root to leaf. Average depth O(log n) for random insertions. Worst case O(n) for sorted input.

Scheme

Tree traversals

Inorder (left, root, right) gives sorted output. Preorder (root, left, right) gives a serialization that can reconstruct the tree. Postorder (left, right, root) evaluates expressions bottom-up.

Scheme
Neighbors

Cross-references