Skip to content
BytePatterns

Root To Leaf Target Sum

EasyTrees & BST#dfs#recursion~20m

Problem

Given a binary tree and a target number, decide whether some path from the root down to a leaf has values adding up exactly to the target. A leaf is a node with no children, so a path must always end at the bottom of the tree. Values may be negative.

Examples

Input:  tree = 5, left 4 with left child 11 having children 7 and 2,
        right 8 with children 13 and 4; target = 22
Output: True
Why:    the path 5, 4, 11, 2 adds up to 22
Input:  tree = 1 with a single left child 2; target = 1
Output: False
Why:    the root is not a leaf, so the path cannot stop there
Input:  tree = empty; target = 0
Output: False
Why:    edge case, an empty tree has no root-to-leaf path at all

Hints

0 / 3

Stuck on the idea rather than the code? Path Sum Variants covers it.