Path Sum II is a classic tree traversal problem that challenges you to find all root-to-leaf paths in a binary tree where the sum equals a target value.

🎯 Your Mission: Given a binary tree and a target sum, discover every possible path from root to leaf where the node values add up exactly to your target.

πŸ“‹ What You're Given:
β€’ root - The root node of a binary tree
β€’ targetSum - An integer representing your target sum

πŸ“€ What You Return:
β€’ A list of lists, where each inner list contains the node values of a valid path
β€’ Each path must start at the root and end at a leaf node
β€’ The sum of values in each path must equal targetSum

🌳 Remember: A leaf node has no children, and you need the actual node values, not references!

Input & Output

example_1.py β€” Basic Tree
$ Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
β€Ί Output: [[5,4,11,2],[5,8,4,1]]
πŸ’‘ Note: There are two paths whose sum equals 22: 5+4+11+2=22 and 5+8+4+1=22. Both start from root and end at leaf nodes.
example_2.py β€” Single Node
$ Input: root = [1,2,3], targetSum = 5
β€Ί Output: []
πŸ’‘ Note: No root-to-leaf path sums to 5. The paths are [1,2] (sum=3) and [1,3] (sum=4).
example_3.py β€” Single Node Match
$ Input: root = [1], targetSum = 1
β€Ί Output: [[1]]
πŸ’‘ Note: The only path is [1] which sums to 1, matching our target.

Visualization

Tap to expand
548114271Energy Budget: 22Path 1: 5β†’4β†’11β†’2 = 22 βœ“Path 2: 5β†’8β†’4β†’1 = 18 βœ—
Understanding the Visualization
1
Start Journey
Begin at the mountain base (root) with full energy budget
2
Follow Trails
At each junction, spend energy (add node value) and choose a path
3
Reach Summit
When you reach a dead-end trail (leaf), check if energy spent equals budget
4
Backtrack
Return to previous junction to explore other trails
Key Takeaway
🎯 Key Insight: Backtracking allows us to explore all possible paths efficiently by building solutions incrementally and undoing choices when we need to try different alternatives.

Time & Space Complexity

Time Complexity
⏱️
O(n)

We visit each node once. In worst case, we might need to copy O(n) paths, each of length O(log n) to O(n)

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

Recursion depth is limited by tree height h. Additional space for storing result paths

n
2n
βœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [0, 5000]
  • βˆ’1000 ≀ Node.val ≀ 1000
  • βˆ’1000 ≀ targetSum ≀ 1000
Asked in
Amazon 45 Microsoft 38 Google 35 Meta 28
68.3K Views
High Frequency
~15 min Avg. Time
2.2K 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