Binary Tree

Path Sum Visualizer

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.

Carry the remainderAt a node, the next target is target minus the node's value. The children do not see the original target.
Stop at a leafA non-leaf cannot answer yes just because the running sum matches. Both children must be missing.

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 path in blue, and the sum so far
def found(node, target):
if node is null: return False
target = target - node.val
if node is a leaf: return target == 0
return found(left, target) or found(right, target)
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Every node is checked at most once.
Call stackO(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)