Intuition
Carry the remaining target down: each node subtracts its value and asks its children to cover the rest. At a leaf, the answer is exact: does the leaf's value equal what's left?
Root-to-leaf questions are top-down recursion: carry a running value into the call rather than returning one up. Subtracting as you descend means the leaf test is a single comparison against zero-remaining. The tell for this family is any phrase like "a path from the root to a leaf" — the answer is decided at leaves, so the leaf definition is the part to get exactly right.
Approach
Subtract as you descend
hasPath(node, t) → at a leaf, check t == node.val; otherwise recurse with t − node.val.
Leaf check is strict
The path must END at a leaf — a null child alone doesn't qualify, which is why the leaf test comes before recursing.
OR over children
Either subtree may complete the path; short-circuit on the first success.
Solution & live demo
Common pitfalls
Treating any node with a null child as a leaf
if not root.left or not root.right:
return targetSum == root.valif not root.left and not root.right:
return targetSum == root.valA node with one child is not a leaf — the path must keep going. With or, a half-empty node ends the path early and reports a sum for a path that never reached a leaf. A leaf has both children missing.
Returning true when the running sum hits zero mid-path
if targetSum == 0: return True
if not root.left and not root.right:
return targetSum == root.valThe target must be met exactly at a leaf, not anywhere along the way. Values can be negative, so a path can hit the target mid-way and then move off it — stopping early answers a different question.
Returning true for an empty tree
if not root: return targetSum == 0
if not root: return False
A null node isn't a leaf and represents no path at all. Returning true there makes any node with one missing child succeed through its empty side, regardless of the values.
Edge cases
No root-to-leaf path exists → False even for target 0.
No pruning on sign — the target can recover; explore fully.