DSA AnimatorDSA animations
Binary Tree Inorder Traversal LC #94 Easy Tree ยท Stack
Problem

Given the root of a binary tree, return the inorder traversal of its values: left subtree โ†’ node โ†’ right subtree. Follow-up: do it iteratively instead of recursively.

Example 1
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,2,6,5,7,1,3,9,8]
Constraints: 0 โ‰ค nodes โ‰ค 100  |  โˆ’100 โ‰ค Node.val โ‰ค 100
๐ŸŒณ Tree
Level order, like LeetCode: 1,null,2,3 ยท up to 15 nodes
๐Ÿ“š stack
curr waiting on stack visited โˆ… null, so stop diving โฌ‡๏ธ visited values drop straight down: left-to-right = inorder
Variables
curr
โ€”
stack size
0
res
[]
๐Ÿ’ก Step Logic
Press โ–ถ Play or Next to begin.
โœ“
Ready
0 / 0
Pick an example and press Play.
Algorithm
1
โฌ…๏ธ While curr isn't null: push it ๐Ÿ“š and go left
2
โˆ… Hit null โ†’ pop the top and visit it โœ…
3
โžก๏ธ Move to its right child and repeat until curr is null and the stack is empty
Time
O(n)
Space
O(h) stack
๐Ÿง  Why it works

Recursive inorder is go(left); visit(node); go(right). The stack stores exactly the nodes whose go(left) call is still running. Each node is pushed once and popped once, so the whole traversal is O(n). Bonus: on a BST, inorder gives the values in sorted order, which is behind "Validate BST" (98) and "Kth Smallest" (230).

โš ๏ธ Edge cases & follow-ups

Empty tree โ†’ [] (the loop never runs). Left-skewed tree โ†’ stack grows to n, so worst-case space is O(n). Loop condition must be curr != null || !stack.isEmpty(): either one alone stops too early. Morris traversal gets O(1) extra space by temporarily threading right pointers.

How to solve Binary Tree Inorder Traversal

LeetCode 94 ยท Easy ยท Tree ยท Pattern: Inorder with Stack

Why the obvious approach is slow

The recursive version is only three lines, but the interviewer often asks for the iterative one. The iterative version uses an explicit stack in place of the call stack.

The key idea

Start at the root, and keep going left, pushing every node on the stack. When you cannot go left any more, pop the top node and record it. Then move to its right child, and repeat the same process from there. Stop when the current node is null and the stack is empty.

Remember

Go left as far as you can, pop, record, then go right. Inorder of a binary search tree is sorted.

Run the animation above on your own input, or watch the 1:57 video explanation of Binary Tree Inorder Traversal with a dry run and Java code.

More Tree problems