A book's table of contents lists a chapter first, then the sections inside it, and only then the next chapter. Calculating the size of a folder goes the other way: each subfolder is measured first, and only then do you know the total for the folder above it. Both read a tree (chapters inside a book, folders inside a folder), only in a different order.
Visiting every node of a tree, each one exactly once, in a particular order is called tree traversal. Here, visiting a node means writing its value down. The tree is a binary tree: the node at the top is the root, each node has at most two children (left and right), and a node with no children is a leaf. The order matters, because each order suits a different job.
One tree, three orders
Here is one tree and its three traversal orders:
1 Pre-order 1, 2, 4, 5, 3, 6, 7
/ \ In-order 4, 2, 5, 1, 6, 3, 7
2 3 Post-order 4, 5, 2, 6, 7, 3, 1
/ \ / \
4 5 6 7
The three orders differ in just one thing: when a node is written down, compared with its left and right subtrees. A subtree is one child together with all the nodes below it. For example, the left subtree of 1 holds 2, 4 and 5.
- Pre-order: the node first, then the left subtree, then the right subtree. That's why 1 comes out first. This is the order of a book's table of contents.
- In-order: the left subtree, then the node, then the right subtree. That's why 1 sits in the middle.
- Post-order: the left subtree, the right subtree, and the node last. That's why 1 comes out last. This is the order for calculating a folder's size.
The same rule applies again inside every subtree. For example, in-order runs like this from the root:
| Step | Where | What happens | Output so far |
|---|---|---|---|
| 1 | 1 | has a left child, go down to 2 first | (empty) |
| 2 | 2 | has a left child, go down to 4 first | (empty) |
| 3 | 4 | a leaf: write 4 | 4 |
| 4 | 2 | left is done: write 2, then go right (5) | 4, 2 |
| 5 | 5 | a leaf: write 5 | 4, 2, 5 |
| 6 | 1 | left subtree is done: write 1, then go right (3) | 4, 2, 5, 1 |
Then the right subtree goes the same way: 6, 3, 7. There's also level-order: nodes are written level by level from the top, and left to right in each level (1, 2, 3, 4, 5, 6, 7). Level-order uses a queue, and in the lesson Graph: BFS & DFS it appears again under the name BFS.
Writing it with recursion
This code builds the same tree, then runs in-order with recursion:
const node = (value, left = null, right = null) => ({ value, left, right });
const root = node(1, node(2, node(4), node(5)), node(3, node(6), node(7)));
function inorder(t, out = []) {
if (!t) return out; // an empty spot: nothing to write
inorder(t.left, out); // 1. the left subtree
out.push(t.value); // 2. this node
inorder(t.right, out); // 3. the right subtree
return out;
}
console.log(inorder(root)); // [4, 2, 5, 1, 6, 3, 7]
node(...)is a short function that makes one node: an object holdingvalue,leftandright. A child that isn't given isnull.inordercalls itself for the left subtree and the right subtree, which are smaller parts of the tree. That's called recursion.if (!t) return out;is the base case, where the recursion stops.!tistruewhentis empty (null), so at anullchild nothing gets written.out = []makes an empty array on the first call, and that same array is then passed along to every call. Eachpushadds one value to it.
If you move out.push(t.value) above the two inorder calls, you get pre-order. If you move it below both, you get post-order. Every node is visited exactly once, so the time is O(n): twice as many nodes takes roughly twice as long.
In the exercise, the tree is the same one without 6 and 7. The nodes are made with new TreeNode(...), and the function is called inOrder. That tree's in-order is 4, 2, 5, 1, 3. Another correct way: each call returns its own array, and the left result, the node's value and the right result are joined with spread (..., which copies the items of an array): [...inOrder(node.left), node.value, ...inOrder(node.right)], with [] for an empty spot.
In-order on a BST: sorted output
In a BST, all the values in a node's left subtree are smaller than the node, and all the values in its right subtree are bigger (or equal). In-order always visits the left, then the node, then the right, so the numbers come out from smallest to largest. For example, fill the same tree shape as a BST: 4 at the root, 2 and 6 below it, then 1, 3, 5, 7. Its in-order is 1, 2, 3, 4, 5, 6, 7.
⚠️ Why does the traversal crash or leave gaps?
- No base case. Without
if (!node) return ..., the function reaches anullchild and readsnull.left, and that crashes right away. - Throwing away the recursive result. If every call makes a new array, the result of
inOrder(node.left)has to be joined in. If you don't use what it returns, all the values of the left subtree are lost. - Not returning an array. In the exercise, the code calls
.join(',')on the result. If the function returnsundefined, including for an empty spot, you get a TypeError.
TL;DR: A tree traversal visits every node of a tree exactly once, in a particular order. The order depends on when a node is written down, compared with its left and right subtrees. Pre-order: node, left, right. In-order: left, node, right. Post-order: left, right, node. In a recursive function (one that calls itself), the only difference is where the line that writes the node goes. The base case if (!node) stops the recursion when it reaches an empty child (null). In-order on a BST (smaller on the left, bigger on the right) gives sorted numbers. Level-order goes level by level from the top, with a queue.
⚡ One tree, three orders
Meaning: A tree traversal visits every node of a tree, each one once. Pre-order, in-order and post-order differ only in when a node is written down, compared with its left and right subtrees. Pre-order: node, left, right, so the root (the top node) comes out first. In-order: left, node, right, so the root sits in the middle. Post-order: left, right, node, so the root comes out last.
⚡ Recursion with a base case
Write:
function inorder(t, out = []) {
if (!t) return out; // an empty spot: nothing to write
inorder(t.left, out); // 1. the left subtree
out.push(t.value); // 2. this node
inorder(t.right, out); // 3. the right subtree
return out;
}
Meaning: inorder is a recursive function: it calls itself for the left and right subtrees. t is the node being visited, and out is the result array. if (!t) is the base case, where the recursion stops: when t is empty (null), nothing is written. If you move out.push(t.value) above the two calls, you get pre-order. If you move it below both, you get post-order.
⚡ In-order on a BST
Guess first: in a BST, the values on a node's left are smaller, and the values on its right are bigger (or equal). Which traversal gives the numbers sorted?
In-order: left (smaller), then the node, then right (bigger). So the numbers come out from smallest to largest.
Meaning: There's also level-order: nodes are written level by level from the top, left to right, with a queue (first in, first out). In the lesson Graph: BFS & DFS, this way is called BFS.