Path Sum - Problem
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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code