Algorithms Made Simple · 4 min read
Folders inside folders, headings inside sections, managers above teams: much of the information we handle is a hierarchy. A tree is the data structure built for it.
The vocabulary
A tree starts at one root. Every other item, called a node, has exactly one parent and can have any number of children. A node with no children is a leaf. The depth of a node is the number of steps down from the root, and the height of the tree is the depth of its deepest leaf.
A tree with n nodes always has exactly n − 1 connections. If you add one more, you create a loop, and it is no longer a tree.
Walking a tree
To visit every node you need a rule for the order. A pre-order walk visits a node before its children, which is how you copy a folder structure. A post-order walk visits children first, which is how you total the size of a folder. A level-order walk goes row by row from the top, using a queue.
Why recursion fits so well
Every child of a node is itself the root of a smaller tree. So “handle this node, then handle each child the same way” describes the whole algorithm. The recursion stops at leaves, which is why it terminates.
Trees you already use
- File systems: folders are internal nodes and files are leaves.
- Web pages: nested elements form a tree that your browser walks to draw the page.
- Organization charts and family trees.
- Decision trees, where each question leads to a branch.
A question to ask
When something has “parts of parts,” ask whether it is really a tree. If it is, you can describe the work once for a node and let the structure repeat it.
