5.1 Binary Tree Inorder Traversal
5.1.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 94
- Difficulty: Easy
- URL: https://leetcode.com/problems/binary-tree-inorder-traversal/
- Tags:
- Techniques: Depth First Search, In-Order Traversal, Stack, Tree
5.1.3 Examples
Example 1: Regular Binary Tree
Input:
1
/ \
2 3
Output: [2,1,3]
Explanation: In-order visits left subtree first (2), then root (1), then right subtree (3)
Example 2: Empty Tree
Input: null
Output: []
Example 3: Skewed Tree
Input:
1
\
2
\
3
Output: [1,2,3]
Explanation: No left children, visits nodes in order down the right spine
5.1.5 Solution - Iterative Stack
5.1.5.1 Walkthrough
Use a stack to simulate recursion and always dive left first:
- Maintain
currentpointer starting at root. - Traverse left spine: push nodes while moving
current = current.leftuntil null. - Pop from stack, record value (the “root” between left and right), then shift to right subtree
current = node.right. - Repeat until both
currentis null and stack is empty.
This yields nodes in left-root-right order without recursion.
5.1.5.3 Code - Java
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
result.add(current.val);
current = current.right;
}
return result;
}5.1.6 Solution - Recursive
5.1.6.1 Walkthrough
Recursively traverse left subtree, visit the current node, then traverse right subtree. This mirrors the inorder definition and appends values in left-root-right order.
The recursive approach is more intuitive and directly reflects the definition of in-order traversal: 1. Base case: If node is null, return immediately 2. Recurse left: Visit all nodes in the left subtree 3. Process current: Add current node’s value to result 4. Recurse right: Visit all nodes in the right subtree
5.1.6.2 Analysis
- Time Complexity: O(n) - Each node is visited exactly once
- Space Complexity: O(h) - Recursion call stack depth where h is tree height (O(n) worst case for skewed tree)