Path Sum III

Medium

Topics
TreeDFSPrefix Sum

Given the root of a binary tree and an integer targetSum (passed as k), return the number of downward paths (parent to child, any start and end node) whose node values sum to k.

Example 1

33-252110-311
one path summing to 8
Paths run downward but need not start at the root or end at a leaf, which is what makes this more than the basic path-sum problem. There are 3.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [10,5,-3,3,2,null,11,3,-2,null,1], k = 8
Output: 3

Example 2

711245138541
one path summing to 22
Input:  root = [5,4,8,11,null,13,4,7,2,null,null,5,1], k = 22
Output: 3

Constraints

  • 0 <= number of nodes <= 1000
  • -10^9 <= Node.val <= 10^9
  • -1000 <= k <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

Paths run downward from any node to any descendant. Along a single root-to-node path, a downward path is just a contiguous run — so the sum of a path ending at the current node equals cur - prefix for some ancestor prefix. This is "count the subarrays summing to k" applied along every root path.

Carry a count of the prefix sums seen on the current path. At each node, the number of qualifying paths ending there is the number of times cur - k has been seen. The word current is the whole trick: the count must be undone on the way back out, or prefixes from one subtree get treated as ancestors of another.

Approach

  1. Seed the prefix count with {0: 1}, so paths starting at the root are counted.
  2. Descend, adding the node's value to the running prefix cur.
  3. Add count[cur - k] to the answer.
  4. Increment count[cur], recurse into both children, then decrement it again.

Dry Run

        10
       /   \
      5     -3
     / \      \
    3   2      11
   / \   \
  3  -2   1

k = 8

  root path              prefix   look for   found   running total
  10                     10       2          0       0
  10 5                   15       7          0       0
  10 5 3                 18       10         1       1      <- 5 -> 3
  10 5 3 3               21       13         0       1
  10 5 3 -2              16       8          0       1
  10 5 2                 17       9          0       1
  10 5 2 1               18       10         1       2      <- 5 -> 2 -> 1
  10 -3                  7        -1         0       2
  10 -3 11               18       10         1       3      <- -3 -> 11

answer 3

Complexity

  • Time — O(n): one visit per node with constant expected map work.
  • Space — O(n). Worth being careful here rather than writing O(h). The recursion is O(h) deep and only h prefix counts are ever live, but a default-valued map is never pruned and the lookup count[cur - k] itself inserts the probed key. On a 1,000-node path the map peaks at 1,999 keys and still holds 1,999 at the end, 1,998 of them zero. Deleting entries as they fall to zero is what makes O(h) true.

Common Pitfalls

  • Omitting the decrement on the way out. On a root of 1 with children 1 and 2 and k = 1, that returns 3 instead of 2 — a prefix recorded in the left subtree is counted as an ancestor of the right one.
  • Forgetting count[0] = 1, which drops every path that starts at the root.
  • Not offering the O(n²) baseline first. Running a separate downward count from every node is the honest naive answer, and at n <= 1000 it even passes; the prefix-count version is the improvement, and it reads better if the baseline is on the board.
  • Overflow. A thousand nodes at magnitudes up to 10⁹ put prefix sums near 10¹², so the running sum and the map keys must be 64-bit.
  • Assuming values are positive and reaching for a sliding window. Negative values are allowed, which is exactly why prefix counting is needed rather than a two-pointer window that relies on monotonicity.
  • Counting upward paths, or paths that bend through a parent. Only downward, parent-to-child paths qualify.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def pathSum(self, root, k):
        from collections import defaultdict
        cnt = defaultdict(int); cnt[0] = 1
        self.total = 0
        def dfs(node, cur):
            if not node: return
            cur += node.val
            self.total += cnt[cur - k]
            cnt[cur] += 1
            dfs(node.left, cur); dfs(node.right, cur)
            cnt[cur] -= 1
        dfs(root, 0)
        return self.total
SensAI
Beta
Tap the mic to stop voice mode