cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 45 of 218
Ideas this builds on
Trees45 / 218

Some information must travel downward

Picture

A node does not always contain enough information to answer a question by itself. If you care about a path from the root, ancestors matter. Pass their relevant effect downward as context; return a result upward. Traversal order follows where the needed information comes from.

Predict

For a root-to-leaf target sum of 15, you have visited nodes valued 8 and 3. What should the next recursive call know: the whole path, the original target, or a remaining target of 4?

Reveal the reasoning

The remaining target 4 is sufficient for an existence question with these fixed rules. If you must output the path itself, you also need a way to reconstruct its nodes.

Go deeper: the contract includes where you are in the visit

Let has_sum(node, remaining) ask whether a path beginning at node and ending at a leaf sums to remaining. The current node has not yet been charged.

def has_sum(node, remaining):
    if node is None:
        return False
    value, left, right = node
    remaining -= value
    if left is None and right is None:
        return remaining == 0
    return has_sum(left, remaining) or has_sum(right, remaining)

tree = (8, (3, None, None), (10, None, None))
assert has_sum(tree, 11)
assert not has_sum(tree, 8)
assert not has_sum(None, 0)

Why is reaching zero at the root not enough? The contract requires a leaf, not merely any prefix. Why is None, 0 false? In this problem, an empty tree has no root-to-leaf path. Base cases express the requested output semantics.

Worst-case time is O(n) and stack space O(h). Short-circuiting can stop early when one branch succeeds.

This information-flow question generalizes: validating a BST passes allowed bounds from ancestors; computing height returns child summaries. Some problems need both directions. Choose the contract before choosing preorder or postorder terminology.

Analogy limit: passing only a remaining sum works because past values affect the answer only through their sum. A rule such as “no repeated value on the path” needs additional context.

Change one rule

Node values may be negative. Is it safe to stop when remaining < 0?

Check the variation

No. A later negative value can make the required sum possible. That pruning rule requires appropriate restrictions, such as all remaining node values being nonnegative.

Connect

DFS visited state asks which traversal history matters. BSTs use inherited bounds. Tree DP returns conditional choices instead of one unconditional summary.