easyTreesPure DSA~14 min
Cost Path To Leaf
A decision tree assigns a cost to each node. Determine whether some root-to-leaf path's costs sum exactly to a given budget.
Problem
Given the root of a binary tree and an integer targetSum, return true if there is a root-to-leaf path whose node values add up to targetSum. A leaf is a node with no children.
Input
The root of a binary tree (0 ≤ nodes ≤ 5000) and integer targetSum; values may be negative.
Output
A boolean — true if such a root-to-leaf path exists.
Constraints
- The path must end at a leaf (no children)
- Node values can be negative
- 0 ≤ number of nodes ≤ 5000
Examples
Example 1
Input
root = [5,4,8,11,null,13,4,7,2], targetSum = 22
Output
true
5 → 4 → 11 → 2 sums to 22.
Example 2
Input
root = [1,2,3], targetSum = 5
Output
false
Root-to-leaf sums are 3 and 4; neither is 5.