Python coding

Downward paths adding to a target

Write count_paths(root, target): count the downward paths in a binary tree whose values add up to target. A downward path starts at any node and follows child links down for zero or more steps, so it may start and end anywhere, but it never goes up. Values can be negative or zero, so a sum that passes the target can come back to it. An empty tree has no paths. Each TreeNode has val, left and right.

The tests call the provided run_count_paths(values, target), where values lists the tree level by level with null for a missing child: [1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3.

Aim for one pass over the tree, not a new search from every node.

Besides the tests, one large input (a 4,695-node tree, 612 levels tall) with a ~130 ms limit (scaled to your device's speed): brute force won't pass.

  • run_count_paths([1,2,3], 3) → 2
  • run_count_paths([4,2,-1,1,3,5,null,null,null,1,null,-4], 5) → 2
  • run_count_paths([], 0) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Think prefix sums. A downward path ending at a node is a suffix of the root-to-node path: its sum is the running total at the node minus the running total just above where it starts.

Hint 2

Carry the running total down and keep a count of each total seen on the current path, starting with {0: 1}. Paths ending here: the count of total - target.

Hint 3

The counts must describe only the current path: add this node's total before visiting its children and take it out on the way back up, or paths leak between branches.

Solution and why it works
pythonO(n) · O(h), h = height
# --- your code ---
def count_paths(root: "TreeNode | None", target: int) -> int:
    totals = {0: 1}                      # running totals on the path from the root, with counts

    def walk(node: "TreeNode | None", total: int) -> int:
        if node is None:
            return 0
        total += node.val
        found = totals.get(total - target, 0)   # paths that end here
        totals[total] = totals.get(total, 0) + 1
        found += walk(node.left, total) + walk(node.right, total)
        totals[total] -= 1               # leaving this node: its total is off the path
        return found

    return walk(root, 0)


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def run_count_paths(values: list[int | None], target: int) -> int:
    return count_paths(build_tree(values), target)

It is the prefix-sum trick for subarrays that sum to k, run on every root-to-node path. A downward path ending at a node starts just below an ancestor whose running total is total - target, so a count of the totals on the current path answers in O(1). Add a node's total before its children and remove it after, so totals from another branch never count. O(n) time, O(h) memory. The trap is a new search from every node: O(n·h), quadratic on a tall tree.