You are handed root, the top node of a binary tree, which may be empty. List the values of all its nodes in inorder: everything in a node's left subtree first, then the node itself, then everything in its right subtree, applied at every node.
Return the values as a list in that order. An empty tree gives an empty list.
Example 1
Input: root = [7, 3, 9, null, 5] Output: [3, 5, 7, 9] Why: 3 and its right child 5 come before 7, and 9 comes after
2 more examples and the constraints
Example 2
Input: root = [2, null, 8, 6] Output: [2, 6, 8] Why: 2 has no left side; 6 is left of 8
Example 3
Input: root = [] Output: [] Why: no nodes, nothing to list
Constraints
- The tree has between 0 and 100 nodes
- −100 ≤ each node value ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- RecursionO(n)
- Explicit stackO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a tree of 100 nodes | Verdict |
|---|---|---|---|
| Recursion | O(n) | Passes; shortest to write | |
| Explicit stack | O(n) | Best; answers the follow-up |
n = number of nodes, h = height of the tree.
Edge cases to test
- Empty tree. [] must return [], and the code must not touch a null root.
- One node. [-4] returns [-4].
- Only left children. [3, 2, null, 1] pushes the whole chain before the first pop, giving [1, 2, 3].
- Only right children. [1, null, 2, null, 3] pops each node straight after pushing it.
Common mistakes
- Appending the node before its left subtree, which gives preorder instead of inorder.
- Ending the loop when the stack is empty while
nodestill points at a right child. - Forgetting to move to
node.rightafter a pop, so the same left chain is pushed forever.
How to talk through it
- 1Clarify. Can the tree be empty? Is it a plain binary tree or a search tree?
- 2Give the recursion. Left, node, right in three lines; O(n) time and O(h) stack.
- 3Explain what the stack holds. Nodes whose left side is still being visited, deepest on top.
- 4Code the iterative loop. Dive left pushing, pop and append, then turn to the right child.
- 5Test out loud. Run the empty tree, a left-only chain and a right-only chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?