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,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
💡 Note: There are two paths whose sum equals 22: 5+4+11+2=22 and 5+8+4+5=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.

Constraints

  • The number of nodes in the tree is in the range [0, 5000]
  • −1000 ≤ Node.val ≤ 1000
  • −1000 ≤ targetSum ≤ 1000

Visualization

Tap to expand
Path Sum II - DFS Approach INPUT Binary Tree Structure 5 4 8 11 13 4 7 2 1 Input Parameters: root = [5,4,8,11,null, 13,4,7,2,null,null,null,1] targetSum = 22 ALGORITHM STEPS 1 Start DFS from Root Init path=[], remaining=22 2 At Each Node Add to path, subtract from sum 3 Check Leaf Node If leaf and sum=0, save path 4 Backtrack Remove node, explore siblings DFS Traversal Trace: Path 1: 5-->4-->11-->2 Sum: 5+4+11+2 = 22 [OK] Path 2: 5-->8-->4-->1 Sum: 5+8+4+1 = 18 [X] Path 3: 5-->8-->4-->1 Sum: 5+8+4+5=22? Check tree Valid paths found: 2 FINAL RESULT Valid Paths Found: Path 1: [5, 4, 11, 2] 5 + 4 + 11 + 2 = 22 Path 2: [5, 8, 4, 1] 5 + 8 + 4 + 1 = 22 Output: [[5,4,11,2],[5,8,4,1]] 2 Valid Paths Found! Time: O(N) | Space: O(H) Key Insight: DFS with backtracking explores all root-to-leaf paths. At each node, we track the current path and remaining sum. When we reach a leaf with remaining sum = 0, we found a valid path. Backtracking ensures we explore all possibilities. TutorialsPoint - Path Sum II | DFS Approach
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