Path Sum
easyTrees & BST II+10 XPTime limit 2s
A hiker walks from the root of a tree down to a leaf (a node with no children), collecting the value of every node on the way. Is there a root-to-leaf walk whose values add up to exactly target?
Tree format. A binary tree is given on one line in level order (top to bottom, left to right), with null for a missing child — the same way most interview platforms show trees. Trailing nulls are left out, and an empty tree is the single word null. Example: 3 9 20 null null 15 7 is
3
/ \
9 20
/ \
15 7
Input: one tree, then a second line target.
Output: true or false (false for an empty tree).
Constraints: 0 ≤ nodes ≤ 10⁴, −1000 ≤ value ≤ 1000, −10⁶ ≤ target ≤ 10⁶. The tree has at most 10⁴ nodes and its height is at most 500, so recursion is safe in every language.
Think about it: subtract each node's value from the target as you go down. At a leaf, check whether what is left is zero. Note that the walk must end at a leaf — stopping halfway does not count.
Sample input 1
5 4 8 11 null 13 4 7 2 null null null 1 22
Sample output 1
true
Sample input 2
1 2 3 5
Sample output 2
false
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).