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
Cave 5Target: 22Cave 4Left: 17Cave 8Left: 14Cave 11Left: 6Cave 13Dead End2Found!Cave Explorer looking for sum = 22Success Path:22 - 5 = 17 (go left)17 - 4 = 13 (go left)13 - 11 = 2 (go right to dead end 2) โœ“
Understanding the Visualization
1
Start at Entrance
Begin with your target sum and enter the cave system
2
Subtract at Each Junction
At each junction, subtract the junction's number from your remaining target
3
Check Dead Ends
When you reach a dead end (leaf), see if your remaining target exactly matches the final number
Key Takeaway
๐ŸŽฏ Key Insight: Instead of calculating sums forward, subtract values backward from the target. When you reach a leaf with remaining sum equal to the leaf's value, you've found a valid path!
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