Imagine you're a treasure hunter navigating through a binary tree where each node represents a checkpoint with a specific value. Your mission is to find if there exists a path from the root (starting point) to any leaf (dead end) where the sum of all values along that path equals your target treasure value.

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

Remember: A leaf is a node with no children - it's where your treasure hunt must end!

Input & Output

example_1.py — Basic Path Sum
$ Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
💡 Note: The root-to-leaf path with target sum 22 is shown: 5 + 4 + 11 + 2 = 22
example_2.py — No Valid Path
$ Input: root = [1,2,3], targetSum = 5
Output: false
💡 Note: There are two root-to-leaf paths: (1 + 2 = 3) and (1 + 3 = 4). Neither equals the target sum of 5.
example_3.py — Empty Tree
$ Input: root = [], targetSum = 0
Output: false
💡 Note: Since the tree is empty, there are no root-to-leaf paths, so return false.

Constraints

  • The number of nodes in the tree is in the range [0, 5000]
  • Node values are in the range [-1000, 1000]
  • -1000 ≤ targetSum ≤ 1000
  • A leaf is a node with no children

Visualization

Tap to expand
Path Sum - DFS Approach INPUT Binary Tree Structure 5 4 8 11 13 4 7 2 1 root = [5,4,8,11,null,13,4, 7,2,null,null,null,1] targetSum = 22 = Path found ALGORITHM STEPS 1 Start DFS at root Begin with node 5, sum=22 2 Subtract node value remaining = 22 - 5 = 17 3 Recurse on children Try left (4) then right (8) 4 Check leaf condition If leaf and sum=0: return true DFS Trace (Valid Path) 5 --> remaining: 22-5=17 4 --> remaining: 17-4=13 11 --> remaining: 13-11=2 2 --> remaining: 2-2=0 OK! Leaf reached, sum = 0 FINAL RESULT Valid Path Found: 5 4 11 2 5+4+11+2 = 22 true Key Insight: DFS naturally explores root-to-leaf paths. At each node, subtract its value from the target sum. When reaching a leaf node, if remaining sum equals 0, a valid path exists. Time: O(n), Space: O(h). TutorialsPoint - Path Sum | DFS Approach
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
58.0K Views
High Frequency
~15 min Avg. Time
2.5K 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