TREES, TRIES & HEAPS / ALGORITHM BRIEF

Tree traversals

A traversal visits every node of a tree exactly once in a specific order.

BeginnerPhase 04 / Topic 2 of 8Mental modelComplexityEdge cases
01

Overview

A traversal visits every node of a tree exactly once in a specific order. Depth-first traversals go deep before wide: preorder (node, left, right), inorder (left, node, right), and postorder (left, right, node). Breadth-first (level order) visits nodes level by level with a queue.

The order is not a detail: it determines what the algorithm can do. Inorder on a BST gives sorted values. Preorder copies or serializes a tree. Postorder computes subtree results before the parent (deleting a tree, sizes, heights). Level order finds the shallowest nodes and per-level answers.

Reading a book's table of contents

Preorder reads a chapter title before its sections. Postorder is like totaling page counts: you can only report a chapter's length after adding up its sections. Level order reads all chapter titles first, then all section titles, and so on.

02

When to use it

  • Preorder: copy, serialize, or print the tree structure; pass information from root to leaves.
  • Inorder: process a BST in sorted order; validate BSTs; kth smallest.
  • Postorder: compute values that depend on children first; free memory; evaluate expression trees.
  • Level order: per-level answers, right side view, minimum depth, shortest distance.
03

Problem patterns it solves

Inorder gives sorted BST values

Recognize it when: BST problems about order: kth smallest, validate, recover swapped nodes.

  • 94. Binary Tree Inorder Traversal
  • 230. Kth Smallest Element in a BST
  • 98. Validate Binary Search Tree
  • 99. Recover Binary Search Tree
Preorder for structure

Recognize it when: serialize, clone, flatten to a list in preorder.

  • 144. Binary Tree Preorder Traversal
  • 297. Serialize and Deserialize Binary Tree
  • 114. Flatten Binary Tree to Linked List
Postorder for subtree results

Recognize it when: the parent needs finished child answers.

  • 145. Binary Tree Postorder Traversal
  • 1325. Delete Leaves With a Given Value
  • 979. Distribute Coins in Binary Tree
Level order per level

Recognize it when: each level's average, max, rightmost, or zigzag order.

  • 102. Binary Tree Level Order Traversal
  • 199. Binary Tree Right Side View
  • 515. Find Largest Value in Each Tree Row
  • 103. Zigzag Level Order Traversal
Traversal pairs rebuild the tree

Recognize it when: construct from preorder + inorder or postorder + inorder.

  • 105. Construct Binary Tree from Preorder and Inorder
  • 106. Construct Binary Tree from Inorder and Postorder
04

Where it is used in real software

Expression evaluation

Postorder of an expression tree gives Reverse Polish Notation, which calculators and compilers evaluate with a stack.

Serialization

Saving a tree to JSON or disk uses preorder with null markers so the structure can be rebuilt exactly.

Garbage collection and cleanup

Deleting a directory tree must delete children before the parent: postorder.

Rendering order

UI frameworks mount components top-down (preorder) and run cleanup bottom-up (postorder).

05

Key terms

Preorder
Node, left, right.
Inorder
Left, node, right.
Postorder
Left, right, node.
Level order
Level by level, left to right, using a queue.
Morris traversal
Inorder in O(1) space by temporarily threading right pointers.
06

Iterative inorder with an explicit stack

  1. 1
    Go left as far as possible

    Push each node while moving to node.left.

  2. 2
    Pop and visit

    The popped node has no unvisited left subtree, so visit it.

  3. 3
    Move to the right child

    Repeat the process on the right subtree.

  4. 4
    Stop

    When the current node is null and the stack is empty.

07

All four orders on one tree

Tree: 4 is the root; 2 (children 1, 3) on the left; 6 (children 5, 7) on the right. This is a BST.

Step 1 / 4
TraversalRuleOutput
Preordernode, left, right4, 2, 1, 3, 6, 5, 7
Inorderleft, node, right1, 2, 3, 4, 5, 6, 7
Postorderleft, right, node1, 3, 2, 5, 7, 6, 4
Level orderlevel by level4 | 2, 6 | 1, 3, 5, 7

NOWTraversal: Preorder | Rule: node, left, right | Output: 4, 2, 1, 3, 6, 5, 7

Inorder printed the BST in sorted order. Preorder starts with the root, and postorder ends with it, which is why either one plus inorder is enough to rebuild the tree.

08

Implementation

function preorder(root, out = []) {  if (!root) return out;  out.push(root.val);  preorder(root.left, out);  preorder(root.right, out);  return out;} function inorderIterative(root) {  const out = [], stack = [];  let node = root;  while (node || stack.length) {    while (node) {      stack.push(node);      node = node.left;    }    node = stack.pop();    out.push(node.val);    node = node.right;  }  return out;} // Postorder iteratively: reverse of (node, right, left)function postorderIterative(root) {  if (!root) return [];  const out = [], stack = [root];  while (stack.length) {    const node = stack.pop();    out.push(node.val);    if (node.left) stack.push(node.left);    if (node.right) stack.push(node.right);  }  return out.reverse();} function rightSideView(root) {  if (!root) return [];  const result = [];  let level = [root];  while (level.length) {    result.push(level.at(-1).val);    const next = [];    for (const node of level) {      if (node.left) next.push(node.left);      if (node.right) next.push(node.right);    }    level = next;  }  return result;}
09

Complexity and performance

Any traversalO(n)

Each node visited once.

DFS spaceO(h)

Stack or recursion depth.

BFS spaceO(w)

w = maximum level width, up to n/2.

Morris traversalO(1) space

Modifies and restores pointers.

10

Trade-offs

DFS vs BFS memory

DFS uses memory proportional to height, BFS proportional to width. Deep narrow trees favor BFS; wide shallow trees favor DFS.

Recursive vs iterative

Iterative traversals are asked in interviews to show you understand the implicit stack.

11

Variants and related techniques

Zigzag level order

Alternate appending left-to-right and right-to-left per level.

Vertical order

Track a column index (left = col - 1, right = col + 1) during BFS.

Boundary traversal

Left boundary, leaves, then right boundary in reverse.

12

Common mistakes

  • Iterative preorder pushing left before right.

    Fix: Push right first so left is popped first.

  • Reading queue length inside the level loop.

    Fix: Capture the level size before processing the level.

  • Rebuilding from preorder and postorder only.

    Fix: Without inorder, the tree is not unique unless it is full.

13

Interview questions

Why does inorder traversal of a BST produce sorted output?

Every value in the left subtree is smaller than the node and every value in the right subtree is larger, so visiting left, node, right visits values in increasing order.

Which two traversals uniquely define a binary tree?

Inorder combined with either preorder or postorder, assuming distinct values.

14

Practice problems

ProblemDifficultyWhat it trains
94. Binary Tree Inorder TraversalEasyIterative stack.
145. Binary Tree Postorder TraversalEasyReverse trick.
102. Binary Tree Level Order TraversalMediumQueue by level.
199. Binary Tree Right Side ViewMediumLast node per level.
230. Kth Smallest Element in a BSTMediumEarly-stopping inorder.
297. Serialize and Deserialize Binary TreeHardPreorder with null markers.