What is Path Sum
A root-to-leaf path adds the values it touches. The question is whether any such path adds up to the target. The path must end at a leaf.
5 4 8 11 -1 13 4 7 2 -1 -1 -1 1 target 22 yes, along 5-4-11-2
Approach
Subtract the current value from the target and ask each child the same question with what remains. A leaf answers yes only when the remaining target is exactly its own value.
The picture keeps the nodes of the path being tried and shows the sum so far. The sample path 5, 4, 11, 2 adds to 22.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Every node is checked at most once. |
| Call stack | O(h) | The path being tried is the recursion. |
Implementation
def found(node, target):
if not node:
return False
target -= node.val
if not node.left and not node.right:
return target == 0
return found(node.left, target) or found(node.right, target)