A binary tree is a hierarchy where each node holds a value and up to two children: left and right. That's the entire definition, and it's the most important non-linear structure in computing. File systems, JSON documents, HTML DOM, organizational charts, decision trees, and (in balanced form) the indexes inside databases are all trees. The top node is the root; nodes with no children are leaves; the height is the longest root-to-leaf path.
Why recursion and trees are soulmates: every subtree of a binary tree is itself a binary tree. "Process the tree" becomes "process this node, then process left subtree, then right subtree", the recursive leap of faith handles everything below you. Most tree algorithms you'll ever write fit in 5–10 lines once the traversal order is chosen correctly.
The four traversals
// Depth-first variants differ ONLY in where the node's own visit happens:
function preOrder(node, visit) { // node → left → right (copying trees, prefixes)
if (!node) return;
visit(node.value);
preOrder(node.left, visit);
preOrder(node.right, visit);
}
function inOrder(node, visit) { // left → node → right (sorted order in a BST!)
if (!node) return;
inOrder(node.left, visit);
visit(node.value);
inOrder(node.right, visit);
}
function postOrder(node, visit) { // left → right → node (deleting trees, suffixes)
if (!node) return;
postOrder(node.left, visit);
postOrder(node.right, visit);
visit(node.value);
}
// Level-order (BFS): a queue, not recursion
function levelOrder(root, visit) {
const queue = root ? [root] : [];
while (queue.length) {
const node = queue.shift(); // FIFO → level by level
visit(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}| Operation / case | Cost | Notes |
|---|---|---|
| Any DFS traversal, n nodes | O(n) | each node visited once |
| Level-order (BFS) | O(n) | each node enqueued once |
| Space: balanced tree DFS | O(log n) | call stack = height |
| Space: degenerate (linked) tree DFS | O(n) | height n, worst case |
| Space: BFS | O(w) | w = max level width, up to n/2 |