Binary Tree Inorder Traversal - Problem
Given the root of a binary tree, return the inorder traversal of its nodes' values.
In an inorder traversal, we visit nodes in the following sequence: Left subtree โ Root โ Right subtree. This traversal pattern is particularly useful for Binary Search Trees as it visits nodes in sorted order!
Goal: Traverse the tree and collect all node values in inorder sequence.
Input: Root node of a binary tree (could be null for empty tree)
Output: Array/list of integers representing node values in inorder sequence
Input & Output
example_1.py โ Basic Binary Tree
$
Input:
[1, null, 2, 3]
โบ
Output:
[1, 3, 2]
๐ก Note:
Tree structure: 1 โ (null, 2 โ (3, null)). Inorder traversal visits: left subtree (empty), root (1), right subtree (3, 2) = [1, 3, 2]
example_2.py โ Empty Tree
$
Input:
[]
โบ
Output:
[]
๐ก Note:
Empty tree has no nodes to traverse, so result is empty array
example_3.py โ Single Node
$
Input:
[1]
โบ
Output:
[1]
๐ก Note:
Tree with only root node: left subtree (empty), root (1), right subtree (empty) = [1]
Visualization
Tap to expand
Understanding the Visualization
1
Start at Root
Begin at the family patriarch, but don't read their name yet
2
Go Left First
Visit all descendants on the left side first, going as deep as possible
3
Read Current Person
Only after visiting all left descendants, read the current person's name
4
Go Right Last
Finally, visit all descendants on the right side
5
Backtrack Up
Return to parent and repeat the process for remaining subtrees
Key Takeaway
๐ฏ Key Insight: Inorder traversal naturally produces sorted output for Binary Search Trees, making it essential for many tree algorithms!
Time & Space Complexity
Time Complexity
O(n)
Each node is pushed and popped exactly once, visiting all n nodes
โ Linear Growth
Space Complexity
O(h)
Stack space equals tree height h. Same as recursive approach but with explicit control
โ Linear Space
Constraints
- The number of nodes in the tree is in the range [0, 100]
- Node values are in the range [-100, 100]
- Follow-up: Can you solve it iteratively without using recursion?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code