Print all "K" Sum paths in a Binary tree

Pattern: Path sums

medium

Count downward paths (from any node to any node below it) whose values sum to k. Keep a map of prefix sums along the current root path: a path ending at this node sums to k exactly when an earlier prefix equals prefix - k.

The problem

Return how many paths sum to k, where a path goes downwards from some node to one of its descendants (or is a single node). The example gives 3. GFG's version prints the paths; this guide counts them, like LeetCode's Path Sum III. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • How many downward paths end at a given node?
  • How can prefix sums give the sum of one of them?
  • What must you undo when leaving a node?

Hints

    Brute force, and why it fails

    Start a walk from every node: O(n × h).

    The key insight

    The same prefix-sum trick as Subarray Sum Equals K works along each root path, with backtracking.

    Dry run

    seen0 10 15 18

    [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], k = 8. Prefix sums on the path 10 → 5 → 3: 10, 15, 18.

    Step 1 of 3

    The plan

    seen = {0: 1}
    count(n, prefix): prefix += n.val
                      found = seen[prefix - k]
                      seen[prefix] += 1; found += count(children); seen[prefix] -= 1
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    One walk with a map.

    Edge cases

    • k = 0 with zeros in the tree.
    • Negative values.
    • A single node equal to k.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int sumK(TreeNode root, int k) {
            Map<Long, Integer> seen = new HashMap<>();   // prefix sums on the path from the root, and how often
            seen.put(0L, 1);
            return count(root, 0, k, seen);
        }
    
        private int count(TreeNode n, long prefix, int k, Map<Long, Integer> seen) {
            if (n == null) return 0;
            prefix += n.val;
            int found = seen.getOrDefault(prefix - k, 0);   // paths ending here whose sum is k
            seen.merge(prefix, 1, Integer::sum);
            found += count(n.left, prefix, k, seen) + count(n.right, prefix, k, seen);
            seen.merge(prefix, -1, Integer::sum);           // leave this path
            return found;
        }
    }

    C++

    class Solution {
    public:
        int sumK(TreeNode* root, int k) {
            unordered_map<long long, int> seen;     // prefix sums on the path from the root, and how often
            seen[0] = 1;
            return count(root, 0, k, seen);
        }
    
        int count(TreeNode* n, long long prefix, int k, unordered_map<long long, int>& seen) {
            if (n == NULL) return 0;
            prefix += n->val;
            int found = seen.count(prefix - k) ? seen[prefix - k] : 0;   // paths ending here whose sum is k
            seen[prefix]++;
            found += count(n->left, prefix, k, seen) + count(n->right, prefix, k, seen);
            seen[prefix]--;                         // leave this path
            return found;
        }
    };

    Python

    class Solution:
        def sumK(self, root, k: int) -> int:
            seen = {0: 1}                           # prefix sums on the path from the root, and how often
    
            def count(n, prefix) -> int:
                if not n:
                    return 0
                prefix += n.val
                found = seen.get(prefix - k, 0)     # paths ending here whose sum is k
                seen[prefix] = seen.get(prefix, 0) + 1
                found += count(n.left, prefix) + count(n.right, prefix)
                seen[prefix] -= 1                   # leave this path
                return found
    
            return count(root, 0)

    Common mistakes

    • Not removing the prefix on the way back.
    • Seeding the map without 0: 1.

    Similar problems