Binary Tree Inorder Traversal (LeetCode 94): Solution and Explanation
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
- Create an empty result list
res, an emptystack, and setcurr = root. - Loop while
curris not null or the stack is not empty. - Inner loop: while
curris not null, pushcurrand move tocurr.left. This stacks up the chain of nodes waiting on their left subtrees. - Pop the top node into
curr. Its left subtree is fully recorded, so appendcurr.valtores. - Set
curr = curr.rightso the next pass explores the right subtree. If it is null, the next pop returns to the nearest waiting ancestor. - When
curris null and the stack is empty, every node has been recorded. Returnres.
Step-by-step example
root = [1,null,2,3]
curr= 1. Push 1 and go left. 1 has no left child, socurrbecomes null. Stack: [1].- Pop 1 and append it.
res= [1]. Move to its right child 2. - Push 2 and go left to 3. Push 3 and go left; 3 has no left child, so
curris null. Stack: [2, 3]. - Pop 3 and append it.
res= [1, 3]. 3 has no right child, socurrstays null. - Pop 2 and append it.
res= [1, 3, 2]. 2 has no right child. curris 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 res1class Solution {
2 public List<Integer> inorderTraversal(TreeNode root) {
3 List<Integer> res = new ArrayList<>();
4 Deque<TreeNode> stack = new ArrayDeque<>();
5 TreeNode curr = root;
6 while (curr != null || !stack.isEmpty()) {
7 while (curr != null) {
8 stack.push(curr);
9 curr = curr.left;
10 }
11 curr = stack.pop();
12 res.add(curr.val);
13 curr = curr.right;
14 }
15 return res;
16 }
17}1class Solution {
2public:
3 vector<int> inorderTraversal(TreeNode* root) {
4 vector<int> res;
5 stack<TreeNode*> st;
6 TreeNode* curr = root;
7 while (curr || !st.empty()) {
8 while (curr) {
9 st.push(curr);
10 curr = curr->left;
11 }
12 curr = st.top();
13 st.pop();
14 res.push_back(curr->val);
15 curr = curr->right;
16 }
17 return res;
18 }
19};Time and space complexity
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.
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 stackonly. At the start the stack is empty whilecurris the root, and after moving right it can be empty whilecurrstill points at a subtree. - Forgetting to set
curr = curr.rightafter 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.