Binary Tree Inorder Traversal

EasyTrees · In-order Traversal🧩 Binary Search Tree & In-orderLeetCode #94 ↗Updated

Problem

Given the root of a binary tree, return the node values in in-order: for every node, first everything in its left subtree, then the node itself, then everything in its right subtree. An empty tree gives an empty list.
Inputroot = [1,null,2,3]Output[1,3,2]
Inputroot = [4,2,6,1,3]Output[1,2,3,4,6]
Inputroot = []Output[]

0 ≤ n ≤ 100  ·  -100 ≤ Node.val ≤ 100  ·  Follow-up: recursion is trivial — can you do it iteratively?

Try it yourself

Java
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
In-order means “go left as far as possible, emit, then step right”. Recursion keeps the return path on the call stack; you can keep it on your own stack, or even inside the tree itself via temporary threads (Morris).
PatternBinary Search Tree & In-order

Instinct The tree is a BST? Its in-order walk is a sorted list and every node splits the search space - think "sorted array in tree form", not "visit everything".

Memory hack Left is less, right is more, in-order reads the sorted score - and every node lives inside a (low, high) fence set by its ancestors.

Open the Binary Search Tree & In-order guide →

Approaches

Brute ForceRecursive DFS

Time O(n)Space O(h)

Direct translation of the definition: recurse left, add the node, recurse right. Each node is visited once; the call stack holds one frame per level, so space is the height h (n for a skewed tree, log n if balanced).

Java
public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    dfs(root, res);
    return res;
}

private void dfs(TreeNode node, List<Integer> res) {
    if (node == null) return;
    dfs(node.left, res);
    res.add(node.val);
    dfs(node.right, res);
}

Three lines and obviously correct, but depth is limited by the call stack.

At a glance

LevelApproachTimeSpace
Brute ForceRecursive DFSO(n)O(h)
BetterIterative with Explicit StackO(n)O(h)
OptimalMorris Traversal (Threaded Tree)O(n)O(1)
Common pitfalls
  • Loop condition while (!stack.isEmpty()) alone — exits before the root is pushed.
  • Morris: forgetting pred.right = null leaves cycles in the caller's tree.
  • Morris predecessor loop without pred.right != curr — spins forever on a thread.
Interview tips
  • Give recursion first, then offer the stack version as the follow-up answer.
  • Mention Morris for O(1) space, and that it mutates the tree during the walk.
  • Note that on a BST, in-order yields values in sorted order.
Pattern
In-order DFS (stack / Morris) → anything needing BST nodes in sorted order or left-root-right processing.
My notes saved in this browser