Skip to main content
Intermediate ~16 min read

Binary Trees & Traversals

Hierarchical data: nodes, subtrees, depth, and the four canonical traversals (pre/in/post-order, level-order).

Prerequisites: Recursion Basics, Big O Notation & Time Complexity

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

traversals.js
// 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 / caseCostNotes
Any DFS traversal, n nodesO(n)each node visited once
Level-order (BFS)O(n)each node enqueued once
Space: balanced tree DFSO(log n)call stack = height
Space: degenerate (linked) tree DFSO(n)height n, worst case
Space: BFSO(w)w = max level width, up to n/2

Check your understanding

  1. 1.Tree: root 1, children (2, 3); 2's children (4, 5). What is the PRE-ORDER sequence?
  2. 2.Which traversal uses a queue instead of recursion's call stack?
  3. 3.Why is post-order the natural choice for deleting/freeing an entire tree?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going