Tree Traversals

How preorder, inorder, postorder and level-order traversals visit a binary tree, when to use each, and what interviewers ask about them.

15 minLesson 2 of 6
On this page
  1. Depth-first orders: preorder, inorder and postorder
  2. Level-order traversal
  3. Time and space complexity
  4. Iterative traversals and other variations
  5. Pitfalls with traversals
  6. In the interview
  7. What to practise next

A tree traversal visits every node of a tree exactly once, in a fixed order. There are four standard orders: preorder, inorder and postorder, which go deep into one branch before the next, and level order, which goes across the tree one depth at a time. Most tree problems come down to choosing the order in which each node can be handled with the information it needs.

Without a defined order you cannot say what "the result" of a walk over the tree is. Printing an outline needs parents before children, summing a folder's size needs the subfolders' sizes first, and listing a search tree in sorted order needs the left side before the right.

Depth-first orders: preorder, inorder and postorder

A depth-first traversal is a recursive function with the shape from Binary Trees: return if the node is empty, recurse into the left child, recurse into the right child. The function reaches every node on the way down, again after finishing the left subtree, and again after finishing the right subtree. The three orders differ only in which of those three moments is used to visit the node, meaning to do the real work such as adding its value to a list.

  • Preorder visits the node, then the left subtree, then the right subtree. Every parent comes before its children, so it suits printing an outline and copying or saving a tree.
  • Inorder visits the left subtree, then the node, then the right subtree. On a binary search tree this produces the values in sorted order.
  • Postorder visits the left subtree, then the right subtree, then the node. Every child comes before its parent, so it suits any calculation where a node needs the answers from its children, such as height, subtree sums and deleting a tree.
B A C pre: B A C in: A B C post: A C B
Walk around the tree and keep it on your left. You pass each node on its left side (preorder), underneath it (inorder) and on its right side (postorder).

Inorder traversal traced by hand

The trace below runs inorder on a small binary search tree. The "calls" row is the call stack, which holds every call that has started and not yet finished. A node stays on the stack until its whole left subtree is done.

Inorder traversalUse the arrows or ← → keys
inorder(node):  if node is empty: return  inorder(node.left)  visit(node)  inorder(node.right)
  1. calls
    08
    output
    83101614

    1Start at 8. Its left subtree has to be finished first, so the call goes left.

  2. calls
    08
    13
    output
    83101614

    2At 3 the same rule applies, so the call goes left again.

  3. calls
    08
    13
    21
    output
    01
    83101614

    3The left child of 1 is empty, so that call returns immediately. Now 1 can be visited.

  4. calls
    08
    13
    output
    01
    13
    83101614

    41 has no right child, so its call finishes. Back at 3 the left subtree is done, so 3 is visited.

  5. calls
    08
    13
    26
    output
    01
    13
    26
    83101614

    5Next comes the right subtree of 3. Node 6 has no left child, so it is visited immediately.

  6. calls
    08
    output
    01
    13
    26
    38
    83101614

    6The calls for 6 and 3 finish. Back at 8 the left subtree is done, so 8 is visited.

  7. calls
    08
    110
    output
    01
    13
    26
    38
    410
    83101614

    7The call goes right to 10. Node 10 has no left child, so it is visited immediately.

  8. calls
    08
    110
    214
    output
    01
    13
    26
    38
    410
    514
    83101614

    8The call goes right to 14, which is a leaf, and visits it.

  9. calls
    output
    01
    13
    26
    38
    410
    514
    83101614
    visits
    6
    deepest stack
    3

    9The traversal is finished. All 6 nodes were visited once, and the stack was never deeper than the height of the tree, which is 3. The output is sorted because this is a binary search tree.

1 / 9

On the same tree, preorder gives 8, 3, 1, 6, 10, 14 and postorder gives 1, 6, 3, 14, 10, 8. In preorder 8 is first because the root is visited before anything else, and in postorder 8 is last because the root needs both subtrees to finish first.

Recursive code

The three functions are identical except for the position of the line that visits the node.

function preorder(node, out = []) {
  if (node === null) return out;
  out.push(node.val);         // visit, then the children
  preorder(node.left, out);
  preorder(node.right, out);
  return out;
}
 
function inorder(node, out = []) {
  if (node === null) return out;
  inorder(node.left, out);
  out.push(node.val);         // visit between the children
  inorder(node.right, out);
  return out;
}
 
function postorder(node, out = []) {
  if (node === null) return out;
  postorder(node.left, out);
  postorder(node.right, out);
  out.push(node.val);         // visit after the children
  return out;
}
def preorder(node, out=None):
    if out is None:
        out = []
    if node is not None:
        out.append(node.val)     # visit, then the children
        preorder(node.left, out)
        preorder(node.right, out)
    return out
 
def inorder(node, out=None):
    if out is None:
        out = []
    if node is not None:
        inorder(node.left, out)
        out.append(node.val)     # visit between the children
        inorder(node.right, out)
    return out
 
def postorder(node, out=None):
    if out is None:
        out = []
    if node is not None:
        postorder(node.left, out)
        postorder(node.right, out)
        out.append(node.val)     # visit after the children
    return out

Level-order traversal

Level order, also called breadth-first traversal, visits all nodes at depth 0, then all nodes at depth 1, and so on, each level from left to right. It is used when the depth of a node matters, for example to return the values grouped by level, to find the shallowest leaf, or to read the tree's right edge.

The method keeps the current level as a list. Each round records the values in that level, then builds the next level from the children of those nodes, left child before right child. The loop stops when a level is empty.

Level-order traversalUse the arrows or ← → keys
level = [root]while level is not empty:  record the values in level  next = children of level, left to right  level = next
  1. level
    08
    next
    83101614
    result
    []

    1The first level contains only the root.

  2. level
    08
    next
    83101614
    result
    [8]

    2Record the values of the current level, which is [8].

  3. level
    08
    next
    03
    110
    83101614
    result
    [8]

    3Collect the children of 8 with the left one first, which gives 3 and 10.

  4. level
    03
    110
    next
    83101614
    result
    [8], [3, 10]

    4The collected nodes become the current level, and their values are recorded.

  5. level
    03
    110
    next
    01
    16
    214
    83101614
    result
    [8], [3, 10]

    5The children of 3 are 1 and 6, and 10 has only the child 14. Because the level is processed from left to right, everything under 3 comes before everything under 10.

  6. level
    01
    16
    214
    next
    83101614
    result
    [8], [3, 10], [1, 6, 14]

    6Record the values of level 2.

  7. level
    next
    83101614
    result
    [8], [3, 10], [1, 6, 14]
    levels
    3

    7All three nodes are leaves, so the next level is empty and the loop stops. Each node was handled once.

1 / 7
function levelOrder(root) {
  const levels = [];
  let level = root === null ? [] : [root];
  while (level.length > 0) {
    levels.push(level.map((node) => node.val));
    const next = [];
    for (const node of level) {
      if (node.left !== null) next.push(node.left);
      if (node.right !== null) next.push(node.right);
    }
    level = next;
  }
  return levels;
}
// [[8], [3, 10], [1, 6, 14]]
def level_order(root):
    levels = []
    level = [] if root is None else [root]
    while level:
        levels.append([node.val for node in level])
        next_level = []
        for node in level:
            if node.left is not None:
                next_level.append(node.left)
            if node.right is not None:
                next_level.append(node.right)
        level = next_level
    return levels
# [[8], [3, 10], [1, 6, 14]]

The other common way to write it uses a single queue: take a node from the front and add its children at the back. To keep the levels apart with that version, read the queue's length at the start of each round and process exactly that many nodes. Breadth-First Search uses the queue form on graphs.

Time and space complexity

ApproachTimeSpaceWhy
Preorder, inorder, postorderO(n)O(h)Each node is visited once. The call stack holds one node for each level of the current path, so h is the height of the tree.
Level orderO(n)O(w)Each node is visited once. w is the width of the widest level, which in a full tree is about half the nodes, so the worst case is O(n).

The height h is about log n in a balanced tree and n in a tree where every node has one child, so the depth-first space cost is O(n) in the worst case. The width w is at most n, and for a very thin tree it is 1. Depth-first uses less memory on a wide, shallow tree, and level order uses less on a tall, thin one.

Iterative traversals and other variations

Iterative depth-first traversal

The recursive versions use the call stack, and on a tree with a hundred thousand nodes in one long chain they overflow it. Python stops much sooner, at a default recursion limit of about 1,000 calls. The fix is to keep your own stack in a loop. For preorder the loop pops a node, visits it and pushes its children. The right child is pushed first so that the left child is popped first.

function preorderIterative(root) {
  const out = [];
  const stack = root === null ? [] : [root];
  while (stack.length > 0) {
    const node = stack.pop();
    out.push(node.val);
    // push right first so that left is popped first
    if (node.right !== null) stack.push(node.right);
    if (node.left !== null) stack.push(node.left);
  }
  return out;
}
def preorder_iterative(root):
    out = []
    stack = [] if root is None else [root]
    while stack:
        node = stack.pop()
        out.append(node.val)
        # push right first so that left is popped first
        if node.right is not None:
            stack.append(node.right)
        if node.left is not None:
            stack.append(node.left)
    return out

Inorder cannot be done by popping and pushing children, because a node must wait until its left subtree is finished. The standard version walks as far left as possible, pushing every node it passes. It then pops a node, visits it, and moves to that node's right child. Repeating this reproduces the recursion exactly.

function inorderIterative(root) {
  const out = [];
  const stack = [];
  let node = root;
  while (node !== null || stack.length > 0) {
    while (node !== null) {      // go as far left as possible
      stack.push(node);
      node = node.left;
    }
    node = stack.pop();
    out.push(node.val);          // visit after the left subtree
    node = node.right;
  }
  return out;
}
def inorder_iterative(root):
    out = []
    stack = []
    node = root
    while node is not None or stack:
        while node is not None:  # go as far left as possible
            stack.append(node)
            node = node.left
        node = stack.pop()
        out.append(node.val)     # visit after the left subtree
        node = node.right
    return out

Iterative postorder is harder to write directly. The usual trick is to run preorder with the children swapped (node, right, left) and reverse the result, which gives left, right, node.

Level order with a queue and its variations

Many questions are a small change to level order. Returning only the last value of each level gives the right-side view of the tree. Reversing every second level gives the zigzag order. Stopping at the first level that contains a leaf gives the minimum depth. In each case the loop is unchanged, and only what is done with each level differs. In JavaScript, array.shift() is a poor queue operation because it moves every remaining element, so use the two-list version above or keep an index to the front of the array.

When a traversal does not apply directly

These orders are defined for trees, where every node has exactly one parent, so each node is reached once. A graph can contain cycles and nodes with several incoming edges, and running the same recursion on it can loop forever or visit nodes more than once. For graphs, keep a set of visited nodes, as described in Depth-First Search and Breadth-First Search.

Inorder also gives sorted values only on a binary search tree. On any other binary tree it lists the nodes from left to right as they are drawn, which has no useful order.

Pitfalls with traversals

In the interview

Several signals in the problem statement point to a traversal. "Visit every node" or "for every node, compute something" means any depth-first order. A calculation where a node needs its children's results, such as height, diameter, or whether the tree is balanced, means postorder. "Sorted order", "k-th smallest" or "validate a search tree" on a binary search tree means inorder. Anything that mentions levels, depth, "closest to the root" or "shortest path" in an unweighted tree means level order.

Questions to expect:

  • "What is the time and space complexity?" The time is O(n) for all four orders because each node is visited once. The space for the depth-first orders is O(h) for the call stack, which is O(log n) on a balanced tree and O(n) on a tree shaped like a linked list. Level order uses O(w) for the widest level, which is up to about n/2.
  • "Can you do it without recursion?" Yes, with an explicit stack. For preorder, pop a node, visit it and push the right child and then the left child. For inorder, push nodes while going left, then pop, visit and move to the right child.
  • "What happens to the recursive version on a tree that is one long chain?" The recursion is as deep as the tree is tall, so a chain of n nodes needs n stack frames and can overflow the call stack. The fix is the iterative version with an explicit stack, which keeps the same O(h) size but lives on the heap and has no fixed depth limit.
  • "Can you traverse in O(1) extra space?" Morris traversal does it by temporarily linking each node's inorder predecessor back to the node, so no stack is needed, and it removes the links as it goes. It takes O(n) time and changes the tree while it runs, so it is not safe if other threads are reading the tree.
  • "Which traversal gives a binary search tree's values in sorted order, and why?" Inorder traversal does, because 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 yields ascending values at every level of the recursion.
  • "Rebuild a tree from its preorder and inorder lists." The first element of the preorder list is the root. Find that value in the inorder list: everything before it is the left subtree and everything after it is the right subtree. The size of the left part tells you how many of the following preorder values belong to the left subtree, so you recurse on both halves. A hash map from value to inorder index avoids searching the list each time. This works only when the values are distinct.
  • "When would you choose breadth-first over depth-first?" Choose breadth-first when the answer depends on the shallowest node or on grouping by level, because it reaches the nearest nodes first and can stop as soon as it finds one. Choose depth-first when the answer is built from the subtrees or when the tree is wide, because it uses memory proportional to the height.
  • "How would you serialize a tree to a string and back?" Write a preorder traversal that includes a marker such as # for every empty child. The marker makes the shape unambiguous, and reading the values back in the same order rebuilds the tree with one recursive function.
Quick check

A tree has root 5, left child 2 and right child 7. Node 2 has a left child 1. What does postorder return?

You need the total size of every folder, where a folder's size is its own files plus all of its subfolders. Which order fits?

A full binary tree has 1,023 nodes on 10 levels. About how many nodes does level order hold in memory at its peak?

Which pair of traversal lists is enough to rebuild a binary tree with distinct values uniquely?

What to practise next

Binary Search Trees arrange values so that you can find, add and remove one without visiting the whole tree. Depth-First Search applies the same ideas to graphs.