M18 · Trees

Tree Traversals: Preorder, Inorder, Postorder and Level Order

A tree has no single natural order, so you choose one. Depth-first traversals go down one branch before the next and differ only in when they visit the node itself; level order sweeps the tree one depth at a time with a queue. Each visits every node once, but they use memory differently and answer different questions.

~40 minIntermediateC# · Python · Java · C++
Curriculum: M18 Trees · 1 of 1 lessons available

You will be able to

  • Use the vocabulary of binary trees: root, child, leaf, subtree, depth and height.
  • Produce the preorder, inorder, postorder and level-order sequences of a tree by hand.
  • Explain how recursion and the call stack implement the depth-first orders, and how a queue implements level order.
  • Derive Θ(n) time for every traversal and the extra space: Θ(h) for depth-first, up to Θ(w) for level order.
  • Choose the right order for a task (copy, sort, delete, shortest path in edges) and switch to an iterative version when the tree is deep.

Helpful before this lesson

  • M09 Queues and Deques — First in, first out, ring buffers, double-ended queues and the monotonic deque.
  • M11 Recursion — Base cases, the call stack, recursion trees and the first look at memoization.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Vocabulary

A tree is a set of nodes connected so that there is exactly one path between any two of them. One node is the root. Every other node has exactly one parent, and the nodes directly below a node are its children. A node without children is a leaf. A node together with everything below it is a subtree.

In a binary tree every node has at most two children, called left and right; the distinction matters, so a node with only a right child differs from one with only a left child.

  • The depth of a node is the number of edges from the root to it. The root has depth 0.
  • The height of a tree is the largest depth of any node. This lesson counts edges, so a single node has height 0. Some books count nodes instead; check the convention before comparing numbers.

The lab's sample tree, given in level order as 8 4 12 2 6 10 14 1 null 5 7, has root 8, height 3, and leaves 1, 5, 7, 10 and 14. It also happens to be a binary search tree, which makes one of the traversals produce something useful.

Reading the input format

The lab builds trees from a level-order list with nulls, the format many problem sites use. Read it left to right, filling the tree one level at a time; null marks a missing child. The children of a missing node are not listed. In the sample, null after 1 says that 2 has no right child, and the next two values, 5 and 7, are therefore the children of 6.

Depth-first: three orders, one recursion

Every depth-first traversal does the same three things at each node: handle the left subtree, handle the right subtree, and visit the node (record it, print it, process it). Only the position of the visit changes.

preorder(node):                inorder(node):                 postorder(node):
    if node is null: return        if node is null: return        if node is null: return
    visit(node)                    inorder(node.left)             postorder(node.left)
    preorder(node.left)            visit(node)                    postorder(node.right)
    preorder(node.right)           inorder(node.right)            visit(node)

On the sample tree:

Order Rule Result
Preorder node, left, right 8 4 2 1 6 5 7 12 10 14
Inorder left, node, right 1 2 4 5 6 7 8 10 12 14
Postorder left, right, node 1 2 5 7 6 4 10 14 12 8

The if node is null: return line is the base case. Every leaf makes two such calls, one per missing child, and the lab shows them as brief "empty subtree" steps.

Watch the call stack panel while stepping through. Each recursive call pushes a frame, and a frame is popped only when both of its subtrees are done. The stack always holds the path from the root to the current node, which is why depth-first traversal needs memory proportional to the height.

What each order is good for

  • Preorder meets a node before anything below it. Use it to copy a tree, to serialize it so it can be rebuilt, or to print an indented outline: a directory listing that shows each folder before its contents is a preorder walk.
  • Inorder on a binary search tree yields the keys in sorted order, because everything in the left subtree is smaller than the node and everything in the right subtree is larger. On a tree that is not a BST, inorder has no special meaning. Checking that an inorder walk is strictly increasing is one way to validate a BST.
  • Postorder meets a node after everything below it. Use it whenever a node's answer depends on its children's answers: subtree sizes, heights, evaluating an expression tree, or freeing a tree (children first, so no pointer is used after its target is gone).

Breadth-first: level order with a queue

Level order visits the root, then every node at depth 1 from left to right, then depth 2, and so on. Recursion cannot do this directly, because the next node to visit is usually in a different subtree. A FIFO queue can:

levelOrder(root):
    queue = empty
    if root is not null: queue.enqueue(root)
    while queue is not empty:
        node = queue.dequeue()
        visit(node)
        if node.left  is not null: queue.enqueue(node.left)
        if node.right is not null: queue.enqueue(node.right)

On the sample: 8 4 12 2 6 10 14 1 5 7. A node's children join the back of the queue, behind every remaining node of the current level, so no node of depth d + 1 is visited before all nodes of depth d. Swap the queue for a stack and you get a depth-first order instead (node, right, left: a mirrored preorder, because the right child is pushed last and popped first), which is a good way to remember why the queue matters.

To process one level at a time (for example, to return a list per level), read the queue's size at the start of each round and dequeue exactly that many nodes before moving on.

Level order also finds the shallowest node that satisfies a condition: the first match it reaches is at the smallest depth. On graphs, the same idea is breadth-first search, which finds shortest paths measured in edges.

Costs

Let n be the number of nodes, h the height and w the largest number of nodes on one level.

Traversal Time Extra space
Preorder, inorder, postorder (recursive) Θ(n) Θ(h) call stack
Level order (queue) Θ(n) Θ(w) queue

Time. Every node is visited once, and each recursive call does constant work besides its two recursive calls. There are n calls on real nodes and n + 1 calls on null children (a binary tree with n nodes has n + 1 missing child slots), so about 2n + 1 calls in total: Θ(n). Level order enqueues and dequeues each node once: Θ(n).

Space. It depends on the tree's shape, which is the interesting part:

  • A balanced tree has h ≈ log₂ n, so depth-first needs only Θ(log n) frames. Its last level holds about half the nodes, so level order can need Θ(n) queue space: (n + 1) / 2 nodes for a perfect tree.
  • A degenerate tree (every node has one child, effectively a linked list) has h = n − 1. Depth-first needs Θ(n) frames, while level order never holds more than one node.

So neither is always cheaper. On the sample tree the call stack holds at most 4 nodes (8, 4, 2, 1), one more frame briefly for a null child, and the queue holds at most 5 nodes.

Deep trees: iterative traversals

The call stack is small and fixed. A degenerate tree with a hundred thousand nodes means a hundred thousand nested calls. CPython stops at its recursion limit (1000 by default, see sys.getrecursionlimit()) with RecursionError. Java throws StackOverflowError. In .NET a stack overflow terminates the process and cannot be caught. In C++ it is undefined behaviour, usually a crash.

The fix is to keep your own stack on the heap:

preorderIterative(root):                 inorderIterative(root):
    stack = [root] if root else []           stack = [], node = root
    while stack:                             while node or stack:
        node = stack.pop()                       while node:                 # go left as far as possible
        visit(node)                                  stack.push(node); node = node.left
        if node.right: stack.push(node.right)    node = stack.pop()
        if node.left:  stack.push(node.left)     visit(node)
                                                 node = node.right

Preorder pushes the right child first so that the left one is popped first. Inorder keeps the path of nodes whose left subtree is still being processed. Postorder is the fiddliest: one common trick runs a "node, right, left" preorder and reverses the output, which gives "left, right, node". The extra space is still Θ(h), but on the heap, where it is limited by memory instead of the thread's stack size. (Morris traversal even gets inorder down to O(1) extra space by temporarily rewiring null right pointers; it is clever but rarely worth the complexity.)

Built-in trees and traversals

None of the four standard libraries has a general-purpose binary tree type you can build node by node. You write a small node class, as the teaching code does. What they do have:

C# Python Java C++
Balanced BST containers SortedSet<T>, SortedDictionary<K,V> none in the standard library TreeSet<E>, TreeMap<K,V> (red-black) std::set, std::map (usually red-black)
Iterating them yields sorted order: an inorder walk sorted order sorted order
Queue for level order Queue<T> collections.deque ArrayDeque<E> std::queue<T>
Stack for iterative DFS Stack<T> list ArrayDeque<E> std::vector<T> or std::stack<T>

Details that matter:

  • Sorted containers are trees. Iterating a SortedSet<T>, TreeMap, or std::map in order is an inorder traversal performed for you, done iteratively with parent pointers or an internal stack.
  • Python's os.walk is a tree traversal of the file system. With topdown=True (the default) it yields each directory before its subdirectories, which is preorder; with topdown=False it yields each directory after them, which is postorder and is what you want for deleting a tree of folders.
  • Java's ArrayDeque is the usual queue for BFS and stack for iterative DFS, but it rejects null elements, so never enqueue a missing child; check for null first, as the teaching code does.
  • C++ ownership: the teaching TreeNode owns its children through std::unique_ptr, so destroying the root frees the whole tree. That destruction is itself recursive, one frame per level, so a very deep tree needs an iterative teardown, the same issue the linked list lesson shows.

The teaching implementation

Each language has a node class, a builder from the level-order format, three recursive depth-first functions that append to an output list, and an iterative level-order function using the language's queue (Queue<T>, deque, ArrayDeque, std::queue). The listings are checked against one shared fixture of trees: empty, a single node, a left chain, a right chain, a full three-node tree, negatives, and the sample BST.

Common mistakes

  • Forgetting the base case, or checking node.left for null but not node itself, which crashes on an empty tree.
  • Expecting inorder to sort any tree. It sorts only binary search trees.
  • Using a stack for level order. You get a depth-first order instead.
  • Recursing on deep or untrusted input: a degenerate tree overflows the call stack.
  • Mixing up the input format: in the level-order list, children of a missing node are not listed, so the positions are not simply 2i + 1 and 2i + 2 once nulls appear.
  • Confusing depth and height conventions (edges vs nodes) when comparing results.

Edge cases

  • Empty tree: every traversal returns an empty sequence; level order never enqueues anything.
  • Single node: all four orders give that one value.
  • Left chain 3 2 null 1: preorder 3 2 1, inorder and postorder 1 2 3. Depth-first space is Θ(n).
  • Right chain 1 null 2 null 3: preorder and inorder 1 2 3, postorder 3 2 1.
  • Duplicate values: traversals do not care; they visit nodes, not distinct values.

Worked practice

1. Give all four orders for the tree 1 2 3 4 5 null 6.

Answer

The tree: 1 has children 2 and 3; 2 has 4 and 5; 3 has only a right child, 6. Preorder: 1 2 4 5 3 6. Inorder: 4 2 5 1 3 6. Postorder: 4 5 2 6 3 1. Level order: 1 2 3 4 5 6.

2. Preorder is 3 9 20 15 7 and inorder is 9 3 15 20 7 (distinct values). Rebuild the tree.

Answer

Preorder's first value, 3, is the root. In the inorder list, everything left of 3 (9) is the left subtree and everything right of it (15 20 7) is the right subtree. Recurse: the right subtree's preorder is 20 15 7, so 20 is its root, with 15 on the left and 7 on the right. In level order: 3 9 20 null null 15 7. Preorder plus inorder always determines a binary tree with distinct values; preorder plus postorder does not (a single child could be left or right).

3. Which order computes the height of every node, and why?

Answer

Postorder. A node's height is 1 + the larger of its children's heights (with −1 for an empty subtree under the edge convention), so both children must be finished before the node is processed.

4. A perfect binary tree has 1,023 nodes. How large do the call stack and the queue get?

Answer

Its height is 9 (2¹⁰ − 1 = 1,023 nodes on 10 levels), so recursion keeps at most 10 node frames, plus one for a null child. The last level holds 512 nodes, so level order's queue reaches about 512 entries. For a perfect tree, depth-first is far cheaper in memory; for a degenerate tree it is the other way round.

Summary

  • Depth-first orders differ only in when the node is visited: before (pre), between (in) or after (post) its subtrees.
  • Level order uses a FIFO queue to sweep the tree one depth at a time.
  • All four are Θ(n) time. Depth-first uses Θ(h) extra space, level order up to Θ(w).
  • Inorder sorts a BST; preorder copies and serializes; postorder combines children's results and frees trees.
  • For deep trees, use an explicit stack instead of recursion.

Full implementation

All four traversal orders in four languages, checked against one shared fixture of trees (empty, single node, skewed, complete, with gaps).

namespace Bekadan.Dsa.Examples.Trees;
 
public sealed class TreeNode(int value)
{
    public int Value { get; } = value;
    public TreeNode? Left { get; set; }
    public TreeNode? Right { get; set; }
 
    /// <summary>Builds a tree from level order with nulls for missing children ([8, 4, 12, null, 6]).</summary>
    public static TreeNode? FromLevelOrder(IReadOnlyList<int?> values)
    {
        if (values.Count == 0 || values[0] is null)
            return null;
        var root = new TreeNode(values[0]!.Value);
        var queue = new Queue<TreeNode>([root]);
        int i = 1;
        while (queue.Count > 0 && i < values.Count)
        {
            var parent = queue.Dequeue();
            if (i < values.Count && values[i++] is int left)
                queue.Enqueue(parent.Left = new TreeNode(left));
            if (i < values.Count && values[i++] is int right)
                queue.Enqueue(parent.Right = new TreeNode(right));
        }
        return root;
    }
}
 
/// <summary>Depth-first (recursive) and breadth-first traversals. Each visits every node once: Θ(n).</summary>
public static class TreeTraversal
{
    public static void Preorder(TreeNode? node, List<int> output)
    {
        if (node is null)
            return;
        output.Add(node.Value);
        Preorder(node.Left, output);
        Preorder(node.Right, output);
    }
 
    public static void Inorder(TreeNode? node, List<int> output)
    {
        if (node is null)
            return;
        Inorder(node.Left, output);
        output.Add(node.Value);
        Inorder(node.Right, output);
    }
 
    public static void Postorder(TreeNode? node, List<int> output)
    {
        if (node is null)
            return;
        Postorder(node.Left, output);
        Postorder(node.Right, output);
        output.Add(node.Value);
    }
 
    public static List<int> LevelOrder(TreeNode? root)
    {
        var output = new List<int>();
        var queue = new Queue<TreeNode>();
        if (root is not null)
            queue.Enqueue(root);
        while (queue.Count > 0)
        {
            var node = queue.Dequeue();
            output.Add(node.Value);
            if (node.Left is not null)
                queue.Enqueue(node.Left);
            if (node.Right is not null)
                queue.Enqueue(node.Right);
        }
        return output;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Trees/TreeTraversal.cs

"""Depth-first (recursive) and breadth-first binary tree traversals: each Θ(n)."""
 
from __future__ import annotations
 
from collections import deque
from collections.abc import Sequence
 
 
class TreeNode:
    __slots__ = ("value", "left", "right")
 
    def __init__(self, value: int) -> None:
        self.value = value
        self.left: TreeNode | None = None
        self.right: TreeNode | None = None
 
    @staticmethod
    def from_level_order(values: Sequence[int | None]) -> TreeNode | None:
        """Build a tree from level order with None for missing children."""
        if not values or values[0] is None:
            return None
        root = TreeNode(values[0])
        queue = deque([root])
        i = 1
        while queue and i < len(values):
            parent = queue.popleft()
            for side in ("left", "right"):
                if i >= len(values):
                    break
                value = values[i]
                i += 1
                if value is not None:
                    child = TreeNode(value)
                    setattr(parent, side, child)
                    queue.append(child)
        return root
 
 
def preorder(node: TreeNode | None, output: list[int]) -> None:
    if node is None:
        return
    output.append(node.value)
    preorder(node.left, output)
    preorder(node.right, output)
 
 
def inorder(node: TreeNode | None, output: list[int]) -> None:
    if node is None:
        return
    inorder(node.left, output)
    output.append(node.value)
    inorder(node.right, output)
 
 
def postorder(node: TreeNode | None, output: list[int]) -> None:
    if node is None:
        return
    postorder(node.left, output)
    postorder(node.right, output)
    output.append(node.value)
 
 
def level_order(root: TreeNode | None) -> list[int]:
    output: list[int] = []
    queue: deque[TreeNode] = deque()
    if root is not None:
        queue.append(root)
    while queue:
        node = queue.popleft()
        output.append(node.value)
        if node.left is not None:
            queue.append(node.left)
        if node.right is not None:
            queue.append(node.right)
    return output

Tested on CPython 3.14.0 · examples/python/dsa_examples/tree_traversal.py

package dev.bekadan.dsa.trees;
 
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
 
/** Depth-first (recursive) and breadth-first binary tree traversals: each Θ(n). */
public final class TreeTraversal {
    private TreeTraversal() {
    }
 
    public static final class TreeNode {
        public final int value;
        public TreeNode left;
        public TreeNode right;
 
        public TreeNode(int value) {
            this.value = value;
        }
 
        /** Builds a tree from level order with nulls for missing children. */
        public static TreeNode fromLevelOrder(List<Integer> values) {
            if (values.isEmpty() || values.get(0) == null) {
                return null;
            }
            TreeNode root = new TreeNode(values.get(0));
            Queue<TreeNode> queue = new ArrayDeque<>(List.of(root));
            int i = 1;
            while (!queue.isEmpty() && i < values.size()) {
                TreeNode parent = queue.remove();
                if (i < values.size() && values.get(i++) instanceof Integer left) {
                    parent.left = new TreeNode(left);
                    queue.add(parent.left);
                }
                if (i < values.size() && values.get(i++) instanceof Integer right) {
                    parent.right = new TreeNode(right);
                    queue.add(parent.right);
                }
            }
            return root;
        }
    }
 
    public static void preorder(TreeNode node, List<Integer> output) {
        if (node == null) {
            return;
        }
        output.add(node.value);
        preorder(node.left, output);
        preorder(node.right, output);
    }
 
    public static void inorder(TreeNode node, List<Integer> output) {
        if (node == null) {
            return;
        }
        inorder(node.left, output);
        output.add(node.value);
        inorder(node.right, output);
    }
 
    public static void postorder(TreeNode node, List<Integer> output) {
        if (node == null) {
            return;
        }
        postorder(node.left, output);
        postorder(node.right, output);
        output.add(node.value);
    }
 
    public static List<Integer> levelOrder(TreeNode root) {
        List<Integer> output = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            output.add(node.value);
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
        return output;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/trees/TreeTraversal.java

#pragma once
 
#include <cstddef>
#include <memory>
#include <optional>
#include <queue>
#include <vector>
 
namespace bekadan::dsa {
 
struct TreeNode {
    int value;
    std::unique_ptr<TreeNode> left;
    std::unique_ptr<TreeNode> right;
    explicit TreeNode(int v) : value(v) {}
 
    // Builds a tree from level order with std::nullopt for missing children.
    static std::unique_ptr<TreeNode> from_level_order(const std::vector<std::optional<int>>& values) {
        if (values.empty() || !values[0]) return nullptr;
        auto root = std::make_unique<TreeNode>(*values[0]);
        std::queue<TreeNode*> queue;
        queue.push(root.get());
        std::size_t i = 1;
        while (!queue.empty() && i < values.size()) {
            TreeNode* parent = queue.front();
            queue.pop();
            if (i < values.size() && values[i++]) {
                parent->left = std::make_unique<TreeNode>(*values[i - 1]);
                queue.push(parent->left.get());
            }
            if (i < values.size() && values[i++]) {
                parent->right = std::make_unique<TreeNode>(*values[i - 1]);
                queue.push(parent->right.get());
            }
        }
        return root;
    }
};
 
// Depth-first (recursive) and breadth-first traversals: each visits every node once, Θ(n).
 
inline void preorder(const TreeNode* node, std::vector<int>& output) {
    if (!node)
        return;
    output.push_back(node->value);
    preorder(node->left.get(), output);
    preorder(node->right.get(), output);
}
 
inline void inorder(const TreeNode* node, std::vector<int>& output) {
    if (!node)
        return;
    inorder(node->left.get(), output);
    output.push_back(node->value);
    inorder(node->right.get(), output);
}
 
inline void postorder(const TreeNode* node, std::vector<int>& output) {
    if (!node)
        return;
    postorder(node->left.get(), output);
    postorder(node->right.get(), output);
    output.push_back(node->value);
}
 
inline std::vector<int> level_order(const TreeNode* root) {
    std::vector<int> output;
    std::queue<const TreeNode*> queue;
    if (root) queue.push(root);
    while (!queue.empty()) {
        const TreeNode* node = queue.front();
        queue.pop();
        output.push_back(node->value);
        if (node->left) queue.push(node->left.get());
        if (node->right) queue.push(node->right.get());
    }
    return output;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/tree_traversal.hpp

References