A root-to-leaf path starts at the root and ends at a leaf, following child links. Given a target integer, decide whether at least one root-to-leaf path has node values that add up to exactly the target.
One line: the binary tree as a level-order array.
The tree is encoded on ONE line as a space-separated level-order (breadth-first) array. The token null marks a missing child; the children of a null are omitted from the array. An empty tree is written as the single token null.
The next line: an integer target.
Print YES if some root-to-leaf path sums to the target, otherwise NO. An empty tree has no root-to-leaf path, so its answer is always NO.
Example 1
Input
10 5 12 3 7 22
Expected
YES
Explanation
The path 10 -> 12 sums to 22 (and so does 10 -> 5 -> 7), so the answer is `YES`.
Example 2
Input
10 5 12 3 7 19
Expected
NO
Explanation
The root-to-leaf sums are 18 (10+5+3), 22 (10+5+7) and 22 (10+12). None equals 19, so `NO`.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →