Learning Outcome
After this lesson, you should be able to explain inorder traversal and write a clean recursive DFS that visits every node once.
Problem Statement
Given the root of a binary tree, return the inorder traversal of its node values. Inorder means: visit left subtree, then current node, then right subtree.
| Input | Output | Why |
|---|---|---|
[1,null,2,3] | [1,3,2] | Visit 1, then the left child of 2, then 2. |
Brute Force Approach
Store root-to-node paths or flatten the tree with a less precise traversal, then try to reorder values later.
This makes the problem harder than needed. Traversal order should be produced directly while visiting the tree.
Optimized Approach
Use DFS recursion. For each node, recursively process the left child, add the current value, then recursively process the right child.
Exact Pseudocode
answer = []
dfs(node):
if node is null:
return
dfs(node.left)
answer.add(node.val)
dfs(node.right)
dfs(root)
return answer
Reference Code
class Solution:
def inorderTraversal(self, root):
answer = []
def dfs(node):
if not node:
return
dfs(node.left)
answer.append(node.val)
dfs(node.right)
dfs(root)
return answerSample Dry Run
| Node | Action | answer |
|---|---|---|
| 1 | Left is null, add 1 | [1] |
| 2 | Go left to 3 before adding 2 | [1] |
| 3 | Add 3 | [1,3] |
| 2 | Add 2 after left subtree | [1,3,2] |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n) | Every node is visited once. |
| Space | O(h) | The recursion stack depends on tree height. |
Edge Cases
- Empty tree returns an empty list.
- Single-node tree returns that one value.
- Skewed tree may have recursion depth O(n).
Interview Checklist
- Remember inorder is left, root, right.
- Add the value between left and right recursion.
- State recursion stack space separately from output space.
FAQs
What is inorder traversal?
It visits the left subtree, then the node, then the right subtree.
Why is recursion natural for trees?
Each subtree is itself a tree, so the same function can solve the same problem on smaller roots.
What is the core pattern?
Recursive DFS traversal.