Chapter 14 · Trees

Tree Traversals

Visiting every node in a tree exactly once. The order matters — the same tree visited in different orders yields different sequences, useful for different problems. Four classical orderings plus Morris traversal for O(1) extra space.

What are in-order, pre-order and post-order traversals?

They're the three depth-first ways to visit every node of a binary tree, named by when the root is visited. Pre-order visits root, left, right (good for copying a tree). In-order visits left, root, right, which gives sorted order in a BST. Post-order visits left, right, root (good for deleting or evaluating). Level-order visits the tree row by row using a queue.

const pre  = (n) => (n ? [n.value, ...pre(n.left), ...pre(n.right)] : []);
const inOrd = (n) => (n ? [...inOrd(n.left), n.value, ...inOrd(n.right)] : []);
const post = (n) => (n ? [...post(n.left), ...post(n.right), n.value] : []);

function levelOrder(root) {               // breadth-first with a queue
  const out = [], q = root ? [root] : [];
  while (q.length) { const n = q.shift(); out.push(n.value); n.left && q.push(n.left); n.right && q.push(n.right); }
  return out;
}

The example tree

4261357

Reference tree used for all traversal examples on this page

In-order (L, Root, R)

1, 2, 3, 4, 5, 6, 7

Pre-order (Root, L, R)

4, 2, 1, 3, 6, 5, 7

Post-order (L, R, Root)

1, 3, 2, 5, 7, 6, 4

Level-order (BFS)

4, 2, 6, 1, 3, 5, 7

Live demo — build and explore a BST

Insert values to build a tree, then think through what in-order, pre-order, and post-order traversal would produce on the shape you created.

Binary Search Tree
preset:
normalpathfounddelete

Tree is empty — insert a value or click a preset above

→ Insert values to build your BST

Recursive traversals

traversals-recursive.pseudo
1inOrder(node): // Left, Visit, Right
2 if node == NULL: return
3 inOrder(node.left)
4 visit(node) // BST: produces sorted output
5 inOrder(node.right)
6 
7preOrder(node): // Visit, Left, Right
8 if node == NULL: return
9 visit(node) // root first = tree serialization
10 preOrder(node.left)
11 preOrder(node.right)
12 
13postOrder(node): // Left, Right, Visit
14 if node == NULL: return
15 postOrder(node.left)
16 postOrder(node.right)
17 visit(node) // children first = safe deletion
18 
19levelOrder(root): // BFS — uses a queue
20 queue <- new Queue
21 queue.enqueue(root)
22 while queue is not empty:
23 node <- queue.dequeue()
24 visit(node)
25 if node.left != NULL: queue.enqueue(node.left)
26 if node.right != NULL: queue.enqueue(node.right)

Iterative in-order (explicit stack)

Recursion uses the call stack implicitly. An explicit stack avoids stack-overflow for deep trees and is useful when you need to pause/resume iteration (e.g., BST iterator).

iterative-inorder.pseudo
1iterativeInOrder(root):
2 stack <- new Stack
3 current <- root
4 while current != NULL or stack is not empty:
5 while current != NULL: // go as far left as possible
6 stack.push(current)
7 current <- current.left
8 current <- stack.pop() // leftmost unvisited node
9 visit(current)
10 current <- current.right // move to right subtree

Morris traversal (O(1) space)

Morris traversal achieves in-order traversal using only O(1) extra space by temporarily modifying the tree (threading predecessor pointers) and then restoring it.

1 / 4
1

No left child

If the current node has no left child, visit it and move to its right child. This handles leaves and nodes with only right children.

1 of 4

Morris traversal pseudocode

morris-inorder.pseudo
1morrisInOrder(root):
2 current <- root
3 while current != NULL:
4 if current.left == NULL:
5 visit(current) // no left: visit and move right
6 current <- current.right
7 else:
8 pred <- current.left // find in-order predecessor
9 while pred.right != NULL and pred.right != current:
10 pred <- pred.right
11 if pred.right == NULL: // first visit: create thread
12 pred.right <- current
13 current <- current.left
14 else: // second visit: remove thread
15 pred.right <- NULL
16 visit(current)
17 current <- current.right

When to use each traversal

In-order

Print BST elements in sorted order, validate a BST, convert BST to sorted array.

Pre-order

Serialize/clone a tree, prefix expression evaluation, directory listings.

Post-order

Delete a tree safely (children before parent), postfix expression evaluation, computing subtree sizes.

Level-order

Find shortest path in unweighted tree, print tree level by level, connect next-pointers in perfect binary tree.

Morris

In-order with O(1) space constraint — embedded systems, very large trees.

Time & space complexity

time — all traversal algorithms visit every node exactly onceO(n)

Linear time

space — recursive/iterative stack depth = tree height hO(h)

O(h) time

space — Morris traversal, no recursion or stackO(1)

Constant time

space — level-order queue in worst case (complete binary tree)O(n)

Linear time

🎯 Quick Check

Which traversal order on a BST produces output in ascending sorted order?

💡Morris traversal restores the tree
Morris traversal temporarily modifies the tree by creating back-pointers from predecessors to successors. It always restores the original structure before finishing. The tree is unmodified after traversal — making it safe to use on read-only trees if you ensure single-threaded access during traversal.

Tree Traversals: summary

Key points

  • All traversals are O(n) time.
  • Recursive depth-first traversal uses O(height) stack space; level-order uses O(width) queue space.
  • Any recursive traversal can be rewritten iteratively with an explicit stack.

Frequently asked questions

›Which traversal gives sorted output?

In-order traversal of a binary search tree visits the values in ascending order.