Given the root of a binary tree, return the inorder traversal of its nodes' values — visit the left subtree, then the node, then the right subtree.
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [1, null, 2, 3] Output: [1, 3, 2] Inorder visits the left subtree (empty), then 1, then its right subtree yielding 3 then 2.
Input: root = [] Output: [] An empty tree has no nodes.
- The number of nodes is in the range [0, 100] - -100 <= Node.val <= 100
Inorder means left, node, right. The recursive version is almost a transcription of that phrase; the iterative version makes the hidden stack explicit — dive left pushing nodes, then pop-visit-and-go-right.
“What is inorder exactly?”
Left subtree, then the current node, then the right subtree.
“Anything special about a BST?”
On a binary search tree, inorder yields the values in sorted order.
Inorder is left, node, right, so I recurse into the left child, record the node, then recurse into the right child.
The iterative version makes the call stack explicit: go left pushing nodes, pop one to visit it, then move to its right child.
Worked example — tree [1, null, 2, 3] (1 with right child 2, whose left child is 3)
1
\
2
/
3
inorder: left of 1 (none) -> 1 -> right subtree of 1
in that subtree: left is 3 -> 2
result: [1, 3, 2]
The traversal is a direct realization of that ordering; the only question is whether you use the call stack (recursion) or an explicit one.
Pushing while walking left and popping to visit reproduces exactly what recursion does implicitly.
Every node is visited once (O(n)); the stack holds at most the current root-to-leaf path (O(height)).
| Iterative (explicit stack) | Recursive | |
|---|---|---|
| Idea | Walk left pushing nodes; pop, visit, go right | dfs(left); visit; dfs(right) |
| Time | O(n) | O(n) |
| Space | O(height) | O(height) |
Both are O(n); the recursive form is the clearest, the iterative form avoids the call stack. Full code is in the Approaches selector below.
Key takeaway
Inorder = left, node, right. Recurse into the left child, record the node, recurse into the right child — or make the stack explicit by walking left and popping to visit. O(n) time, O(height) space.
inorder(node):
if node is null: return
inorder(node.left)
visit(node)
inorder(node.right)