Binary Tree Inorder Traversal (LeetCode 94): Solution and Explanation

Easy
Stack
Tree
Depth First Search
Binary Tree

Given the root of a binary tree, return its node values in inorder order: for every node, list its whole left subtree, then the node, then its whole right subtree. The tree has at most 100 nodes and may be empty.

Intuition

The recursive answer is three lines: traverse the left subtree, record the node, traverse the right subtree. It is correct, but interviewers usually ask for the iterative version, and the way to get there is to ask what the recursion is quietly keeping track of.

When the recursion is deep inside some left subtree, the call stack holds every ancestor that has been entered but not yet recorded. Each of those ancestors is waiting for exactly one thing: its left subtree to finish. That list of waiting ancestors is all the state there is, so an explicit stack can hold it instead.

That gives a simple rhythm. From the current node, keep going left and push every node you pass, because none of them can be recorded until everything to their left is done. When you fall off the tree, the node on top of the stack has nothing unrecorded to its left, so pop it and record it. Then its right subtree is next, so move to the right child and start the rhythm again.

A helpful picture: if you draw the tree so every node sits in its own column with left subtrees further left, inorder is just reading the nodes from left to right. The stack is the machinery that produces that left-to-right reading while only ever following child pointers downward.

Approach: Iterative inorder with an explicit stack

  1. Create an empty result list res, an empty stack, and set curr = root.
  2. Loop while curr is not null or the stack is not empty.
  3. Inner loop: while curr is not null, push curr and move to curr.left. This stacks up the chain of nodes waiting on their left subtrees.
  4. Pop the top node into curr. Its left subtree is fully recorded, so append curr.val to res.
  5. Set curr = curr.right so the next pass explores the right subtree. If it is null, the next pop returns to the nearest waiting ancestor.
  6. When curr is null and the stack is empty, every node has been recorded. Return res.

Step-by-step example

root = [1,null,2,3]
  1. curr = 1. Push 1 and go left. 1 has no left child, so curr becomes null. Stack: [1].
  2. Pop 1 and append it. res = [1]. Move to its right child 2.
  3. Push 2 and go left to 3. Push 3 and go left; 3 has no left child, so curr is null. Stack: [2, 3].
  4. Pop 3 and append it. res = [1, 3]. 3 has no right child, so curr stays null.
  5. Pop 2 and append it. res = [1, 3, 2]. 2 has no right child.
  6. curr is null and the stack is empty, so the loop ends and the function returns [1, 3, 2].

Code: Python, Java, C++

1class Solution:
2    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
3        res = []
4        stack = []
5        curr = root
6        while curr or stack:
7            while curr:
8                stack.append(curr)
9                curr = curr.left
10            curr = stack.pop()
11            res.append(curr.val)
12            curr = curr.right
13        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is pushed onto the stack exactly once and popped exactly once, and each push or pop is constant work, so the total is linear in the number of nodes.

Space

O(h)

The stack holds at most one root-to-leaf chain of left-leaning ancestors, so it is bounded by the tree height h. That is O(log n) for a balanced tree and O(n) for a skewed one. The output list is not counted.

Other approaches

Recursive DFS (time O(n), space O(h))

Recurse into the left child, append the node, recurse into the right child. It is the clearest version and has the same complexity, but it relies on the call stack, which interviewers often ask you to replace.

Morris traversal (time O(n), space O(1))

Temporarily link each node's inorder predecessor back to the node so you can climb back up without a stack, then remove the link on the second visit. It uses constant extra space but modifies the tree during the walk and is harder to get right.

Common mistakes

  • Recording a node when it is pushed instead of when it is popped. That produces preorder, not inorder.
  • Writing the outer loop as while stack only. At the start the stack is empty while curr is the root, and after moving right it can be empty while curr still points at a subtree.
  • Forgetting to set curr = curr.right after recording a node, which makes the loop push the same left chain forever or skip every right subtree.
  • Returning a nil slice in Go for an empty tree. Initialize the result as an empty slice so it serializes as [] instead of null.

Frequently asked questions

Why does the iterative version need both curr and the stack in the loop condition?

Either one can mean work is left. The stack holds ancestors still waiting to be recorded, and curr can point at a right subtree that has not been explored yet even when the stack is empty, as happens right after the root is recorded in a tree with no left side.

How do I turn this into preorder or postorder?

For preorder, record each node when you push it instead of when you pop it. Postorder is easiest by running a mirrored preorder (node, right, left) and reversing the result, or by tracking the last visited node so you only record a node after its right subtree is done.

Why does inorder of a binary search tree come out sorted?

In a BST every value in the left subtree is smaller than the node and every value in the right subtree is larger. Inorder lists the left subtree, then the node, then the right subtree, so values appear in increasing order. That is why problems like Validate BST and Kth Smallest Element in a BST are built on this traversal.

What is the time and space complexity of iterative inorder traversal?

Time is O(n) because each node is pushed and popped once. Extra space is O(h), the height of the tree, for the stack, which becomes O(n) on a completely skewed tree.