Skip to lesson

Preorder, inorder and postorder

Depth-first traversals visit every node in a binary tree by exploring deep branches before backtracking.

The Three Orders: Preorder, Inorder, and Postorder

A depth-first traversal visits a tree by going as deep as possible down one branch before the next: preorder (node, left, right), inorder (left, node, right) or postorder (left, right, node).

Linear collections offer only forward or backward traversal. Trees branch into two subtrees, offering multiple valid traversal sequences. Depth-First Search traverses deeply into subtrees before visiting sibling branches. The position where we process the current node determines the traversal name.

Inorder walk: left, node, right

Step 1 of 7

12345
Visited(empty)
Start at the root, value 1. Inorder goes left first, so nothing is visited yet.

Example 1 · All Three Recursive Traversals

RecursiveDFSDemo.javaJava
public class RecursiveDFSDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    public static void preorder(TreeNode node) {        if (node == null) return;        System.out.print(node.val + " ");        preorder(node.left);        preorder(node.right);    }
    public static void inorder(TreeNode node) {        if (node == null) return;        inorder(node.left);        System.out.print(node.val + " ");        inorder(node.right);    }
    public static void postorder(TreeNode node) {        if (node == null) return;        postorder(node.left);        postorder(node.right);        System.out.print(node.val + " ");    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.left = new TreeNode(4);        root.left.right = new TreeNode(5);
        System.out.print("Preorder: "); preorder(root); System.out.println();        System.out.print("Inorder: "); inorder(root); System.out.println();        System.out.print("Postorder: "); postorder(root); System.out.println();    }}
Output
Preorder: 1 2 4 5 3 
Inorder: 4 2 5 1 3 
Postorder: 4 5 2 3 1 

What this code does

  • Preorder prints the node before recursing into left and right subtrees.
  • Inorder prints between subtrees, and postorder prints after both subtrees.

In preorder traversal, we process the node first, then traverse left, then traverse right. In inorder traversal, we traverse left first, process the node, then traverse right. In postorder traversal, we traverse left first, traverse right, and process the node last. All three traversals visit every node exactly once in O(n) time. Trace all three orders on tree with root 1, left 2, right 3. Preorder visits root first: [1, 2, 3]. Inorder visits left first, then root, then right: [2, 1, 3]. Postorder visits children first before root: [2, 3, 1].

What Each Traversal Order Is Used For

Each traversal order serves distinct algorithmic purposes in computer science. Preorder traversal visits parents before children. This top-down sequence makes preorder ideal for serializing a tree or creating an identical clone. It also mirrors the structure of directory path listings.

Postorder walk: left, right, node

Step 1 of 7

12345
Visited(empty)
Postorder visits a node only after both of its children. Start at the root, value 1.

Example 2 · Collecting Inorder Traversal into a List

InorderCollectorDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class InorderCollectorDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    public static List<Integer> inorderTraversal(TreeNode root) {        List<Integer> result = new ArrayList<>();        helper(root, result);        return result;    }
    private static void helper(TreeNode node, List<Integer> result) {        if (node == null) return;        helper(node.left, result);        result.add(node.val);        helper(node.right, result);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(4);        root.left = new TreeNode(2);        root.right = new TreeNode(6);        root.left.left = new TreeNode(1);        root.left.right = new TreeNode(3);
        System.out.println("Inorder list: " + inorderTraversal(root));    }}
Output
Inorder list: [1, 2, 3, 4, 6]

What this code does

  • Passes an accumulator list through recursive calls to gather values in order.
  • Yields a sorted list when the input tree satisfies search tree invariants.

Example 3 · Bottom-Up Subtree Size via Postorder

SubtreeSizeDemo.javaJava
public class SubtreeSizeDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    public static int calculateSizes(TreeNode root) {        if (root == null) return 0;        int leftSize = calculateSizes(root.left);        int rightSize = calculateSizes(root.right);        int total = 1 + leftSize + rightSize;        System.out.println("Node " + root.val + " subtree size: " + total);        return total;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.left = new TreeNode(4);
        calculateSizes(root);    }}
Output
Node 4 subtree size: 1
Node 2 subtree size: 2
Node 3 subtree size: 1
Node 1 subtree size: 4

What this code does

  • Calculates child subtree sizes first before computing the parent size.
  • Demonstrates postorder bottom-up synthesis for subtree properties.

Inorder traversal visits left, root, then right. When applied to a Binary Search Tree, inorder traversal visits elements in strictly sorted ascending order. This makes inorder essential for verifying search tree invariants and finding kth smallest items. It converts a search tree into a sorted sequence in linear time. Postorder traversal processes children before their parent. This bottom-up order is required when deleting a tree, freeing children before removing parents. It is also used for evaluating mathematical expression trees and computing subtree heights. Parents can only calculate results after their children have completed computation.

Time and Space Complexity of Recursive Traversals

Every recursive traversal visits each of the n nodes exactly once. At each node, it performs constant O(1) work. Therefore, time complexity is always O(n) across all three traversal orders. No node is visited more than a constant number of times.

The space complexity is determined by the maximum depth of the call stack. For a balanced binary tree, the height is approximately log₂(n). Thus, balanced trees use O(log n) auxiliary stack space. In the worst case of a skewed tree, the height reaches n.

A skewed tree consumes linear O(n) stack memory. If a tree contains 100,000 skewed nodes, deep recursion can trigger a StackOverflowError. In production systems, deep trees are handled using iterative stack traversals. Understanding recursive stack depth is essential for writing robust tree algorithms.

Predict the output

Which order prints?

Trace the recursion, then pick the output.

Round 1 of 3

Tree: root 1 with left child 2 and right child 3. What does visit(root) print?

static void visit(TreeNode node) {
if (node == null) return;
visit(node.left);
visit(node.right);
System.out.print(node.val + " ");
}

Next step

Check your understanding

10 quick questions