Tech Interview RoomStudy guides

Trees

Binary tree traversals (inorder, preorder, postorder). Compare recursion, an explicit stack and Morris traversal.

Intermediate · 2 min read · Lesson 3 of 5 in Trees

Problem

Return the inorder traversal of a binary tree (left, node, right), and know how to adapt for preorder and postorder.

Pattern

Depth-first traversal: recursion uses the call stack; the iterative version makes the stack explicit (important for very deep trees); Morris traversal temporarily threads the tree to use O(1) extra space.

java
final class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; }
    TreeNode(int val) { this(val, null, null); }
}

Approach 1: Recursive (O(n) time, O(h) stack)

java
import java.util.ArrayList;
import java.util.List;

class TraverseRecursive {
    static List<Integer> inorder(TreeNode root) { List<Integer> out = new ArrayList<>(); in(root, out); return out; }
    private static void in(TreeNode n, List<Integer> out) {
        if (n == null) return;
        in(n.left, out);
        out.add(n.val);                                          // move this line for pre-/postorder
        in(n.right, out);
    }
}

Approach 2: Iterative with an explicit stack (O(n), O(h))

java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

class TraverseIterative {
    static List<Integer> inorder(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) { stack.push(cur); cur = cur.left; }   // go as far left as possible
            cur = stack.pop();
            out.add(cur.val);
            cur = cur.right;
        }
        return out;
    }

    static List<Integer> preorder(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        Deque<TreeNode> stack = new ArrayDeque<>();
        if (root != null) stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode n = stack.pop();
            out.add(n.val);
            if (n.right != null) stack.push(n.right);            // right first so left is processed first
            if (n.left != null) stack.push(n.left);
        }
        return out;
    }

    // Postorder = reverse of a (node, right, left) preorder
    static List<Integer> postorder(TreeNode root) {
        LinkedList<Integer> out = new LinkedList<>();
        Deque<TreeNode> stack = new ArrayDeque<>();
        if (root != null) stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode n = stack.pop();
            out.addFirst(n.val);
            if (n.left != null) stack.push(n.left);
            if (n.right != null) stack.push(n.right);
        }
        return out;
    }
}

Approach 3: Morris inorder traversal (O(n) time, O(1) extra space)

For each node with a left subtree, link its inorder predecessor's right back to it, descend left, and remove the link on the way back. The tree is restored afterwards.

java
import java.util.ArrayList;
import java.util.List;

class TraverseMorris {
    static List<Integer> inorder(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        TreeNode cur = root;
        while (cur != null) {
            if (cur.left == null) { out.add(cur.val); cur = cur.right; continue; }
            TreeNode pred = cur.left;
            while (pred.right != null && pred.right != cur) pred = pred.right;
            if (pred.right == null) { pred.right = cur; cur = cur.left; }      // create thread
            else { pred.right = null; out.add(cur.val); cur = cur.right; }     // remove thread
        }
        return out;
    }
}

class TraversalDemo {
    public static void main(String[] args) {
        //        4
        //      /   \
        //     2     6
        //    / \   / \
        //   1   3 5   7
        TreeNode root = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(3)), new TreeNode(6, new TreeNode(5), new TreeNode(7)));
        System.out.println(TraverseRecursive.inorder(root) + " " + TraverseIterative.inorder(root) + " " + TraverseMorris.inorder(root));
        System.out.println(TraverseIterative.preorder(root) + " " + TraverseIterative.postorder(root));
        // [1..7] x3 ; [4, 2, 1, 3, 6, 5, 7] [1, 3, 2, 5, 7, 6, 4]
    }
}

Feasible → optimal

All are O(n) time. Recursion is simplest (O(h) stack, overflow risk on skewed trees); the iterative stack is robust; Morris uses O(1) extra space at the cost of temporarily modifying the tree (not safe for concurrent readers).

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): kth smallest element in a BST.

Iterative inorder and stop after popping k nodes: O(h + k) time, O(h) space. If the tree changes often and queries are frequent, augment each node with its subtree size and walk down in O(h).

Related (same pattern): flatten a binary tree to a linked list in preorder.

Reverse postorder (right, left, node) with a prev pointer: set node.right = prev, node.left = null, prev = node. Or a Morris-like O(1) approach: for each node with a left child, attach its right subtree to the rightmost node of the left subtree, then move the left subtree to the right.