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
FBGADICEH1. Start leftmostInorder Result: A โ†’ B โ†’ C โ†’ D โ†’ E โ†’ F โ†’ G โ†’ H โ†’ INotice: For BST, this gives sorted order!Traversal Order:1. Go leftmost (A)2. Parent (B)3. Right child (C)4. Continue pattern...5. Until all visited
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

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Stack space equals tree height h. Same as recursive approach but with explicit control

n
2n
โœ“ 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?
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28 Apple 25
38.9K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen