CS concepts

Tree Traversals Explained: Preorder, Inorder, Postorder, Level

Updated Nov 27, 2026 · 4 min read

There are four ways to walk a binary tree. Preorder visits the root, then left, then right; inorder goes left, root, right, which reads a binary search tree in sorted order; postorder visits both children before the root; level order goes row by row with a queue. The three depth-first walks are the same recursive function with the visit line moved before, between or after the two calls.

Tree Traversals and Recursion reel cover

Key points

  • ●Preorder: root, left, right. Use it to copy or serialize a tree.
  • ●Inorder: left, root, right. A binary search tree comes out sorted.
  • ●Postorder: left, right, root. Use it when a node needs its children's answers first.
  • ●Level order is breadth-first search with a queue, not recursion.
  • ●Recursive stack space is O(h): fine for balanced trees, a crash risk on a 10,000-node chain.
Step-by-step visual sheet: Tree Traversals and Recursion
The full visual sheet, made with Edithly.Open the interactive sheet

One tree, four walks

Every tree question in a coding interview walks the tree in one of four orders. Three of them come from the same five lines of recursion. You just move one line.

A binary tree is a node with a value and up to two children, left and right. Each child is the root of a smaller tree, which is why recursion fits so well: a function that handles a tree can call itself on the left tree and the right tree. When you step past a leaf there's no node, just None, and that's the base case.

The tree used all the way through, also drawn on the visual sheet above:

        4
      /   \
     2     6
    / \   / \
   1   3 5   7

The two questions behind every tree recursion

Before any walk, ask two things:

  1. What do I return for an empty tree?
  2. If my children already gave me their answers, how do I combine them?

Then trust the call: assume the recursive calls already work, and only think about this node. Counting nodes shows it: an empty tree has 0; otherwise it's 1 for me, plus the left count, plus the right count. On the example, each subtree says 3, so the root says 7. You never trace a single call.

The one-line rule

def walk(node):
    if not node:
        return
    # visit(node) here for preorder
    walk(node.left)
    # visit(node) here for inorder
    walk(node.right)
    # visit(node) here for postorder

Visit before the two calls and you get preorder. Between them, inorder. After them, postorder.

Walk Order On the example Use it for
Preorder root, left, right 4 2 1 3 6 5 7 Copying or serializing a tree
Inorder left, root, right 1 2 3 4 5 6 7 Sorted values on a binary search tree
Postorder left, right, root 1 3 2 5 7 6 4 When a node needs its children's answers first
Level order row by row [4] [2, 6] [1, 3, 5, 7] Anything about rows or the shallowest node

Preorder, inorder, postorder

Preorder visits a node the moment it arrives, before its children. Use it to copy a tree or write it out to rebuild later, since the parent must exist before its children. LeetCode 297, Serialize and Deserialize Binary Tree, writes the tree out in preorder with a marker for each missing child.

Inorder gives 1 through 7, sorted. That's because the example is a binary search tree, where everything left of a node is smaller and everything right is bigger. LeetCode 230, Kth Smallest Element in a BST, falls out of it: walk inorder and count, and the kth node you visit is the answer.

Postorder puts the root last. Use it when a node needs its children's answers first: height, size, or deleting a tree, where you can't free a parent before its kids. Most interview recursion is secretly postorder, since "ask the children, then combine" is exactly that.

Level order: a queue, not recursion

The fourth walk goes sideways, row by row. It's breadth-first search:

from collections import deque

def level_order(root):
    rows, q = [], deque([root] if root else [])
    while q:
        level = [q.popleft() for _ in range(len(q))]
        rows.append([n.val for n in level])
        for n in level:
            if n.left:
                q.append(n.left)
            if n.right:
                q.append(n.right)
    return rows

len(q) at the start of each round is the trick: it's exactly the number of nodes on the current row. That's LeetCode 102 almost line for line, and it returns [[4], [2, 6], [1, 3, 5, 7]] on the example.

Two problems: Maximum Depth and Validate BST

LeetCode 104, Maximum Depth. Empty tree, depth 0. Otherwise, 1 plus the bigger child depth. Children first, then combine, so it's postorder. O(n) time, O(h) space.

def max_depth(node):
    if not node:
        return 0
    return 1 + max(max_depth(node.left), max_depth(node.right))

LeetCode 98, Validate BST. The tempting answer checks each node against its own children, and it's wrong. Picture 5 with a right child 6, and 4 as 6's left child: every parent and child pair looks fine, but 4 sits in 5's right subtree while being smaller than 5. The rule covers the whole subtree, so pass a range down. Going left, the node's value becomes the new high; going right, the new low.

def valid(node, low=float("-inf"), high=float("inf")):
    if not node:
        return True
    if not (low < node.val < high):
        return False
    return valid(node.left, low, node.val) and valid(node.right, node.val, high)

The strict < matters, because LeetCode 98 treats a repeated value as invalid. A second approach uses inorder: on a valid tree the values come out strictly increasing, so any drop is the bug.

The Python trap: recursion depth

Every recursive call waits on a stack, and Python stops at about 1,000 deep by default. A balanced tree of 1 million nodes is only about 20 levels tall, so recursion is fine. A tree that's one long chain of 10,000 nodes is 10,000 deep, and the three-line function crashes. That's why tree recursion is O(h) space: about log n when balanced, n for a chain. If the tree could be skewed, use your own stack or the level-order queue.

Frequently asked questions

What is the difference between preorder, inorder and postorder?

Only where you visit the node. Visit it before the two recursive calls for preorder, between them for inorder, and after them for postorder. On the tree 4 (2 (1, 3), 6 (5, 7)) that gives 4 2 1 3 6 5 7, then 1 2 3 4 5 6 7, then 1 3 2 5 7 6 4.

Which traversal gives sorted order?

Inorder, but only on a binary search tree. Everything left of a node is smaller and everything right is bigger, so left, root, right reads the values smallest to biggest. On an ordinary binary tree, inorder has no special order.

Is level order traversal recursive?

Not usually. Level order is breadth-first search with a queue: take out every node on the current row, then add their children. The queue's length at the start of each round tells you how many nodes are on that row.

What is the time and space complexity of tree traversal?

O(n) time, since every node is visited once. Recursive versions use O(h) stack space, where h is the height: about log n for a balanced tree, but n for a tree that is one long chain.

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free