Algo-Sim › Binary Trees & BST

Path Sum III

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Prefix sums along the root-to-node path in a hash map: each node counts the earlier prefixes equal to sum − target, and removes its own on the way back.

Problem

Given the root of a binary tree and targetSum, count the paths whose values add up to targetSum. A path may start and end at any nodes, but must go downward, from parent to child.

Constraints

Edge cases to test

Follow-up questions

Why remove the prefix on the way back up?
Only prefixes on the current root-to-node path are valid starts; leaving them in would count paths that jump between branches.
What is the brute force?
Start a downward DFS from every node: O(n·h), O(n²) on a chain.

Solution

Java

public int pathSum(TreeNode root, int targetSum) {
    Map<Long, Integer> seen = new HashMap<>();
    seen.put(0L, 1);  // the empty prefix above the root
    return count(root, 0, targetSum, seen);
}

private int count(TreeNode node, long sum, int target, Map<Long, Integer> seen) {
    if (node == null) return 0;
    sum += node.val;
    int paths = seen.getOrDefault(sum - target, 0);
    seen.merge(sum, 1, Integer::sum);
    paths += count(node.left, sum, target, seen);
    paths += count(node.right, sum, target, seen);
    seen.merge(sum, -1, Integer::sum);
    return paths;
}

Python

def path_sum(root, target_sum):
    seen = {0: 1}  # the empty prefix above the root
    return count(root, 0, target_sum, seen)


def count(node, total, target, seen):
    if not node:
        return 0
    total += node.val
    paths = seen.get(total - target, 0)
    seen[total] = seen.get(total, 0) + 1
    paths += count(node.left, total, target, seen)
    paths += count(node.right, total, target, seen)
    seen[total] -= 1
    return paths

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int pathSum(TreeNode *root, int targetSum) {
        unordered_map<long long, int> seen;
        seen[0] = 1;
        return count(root, 0, targetSum, seen);
    }

  private:
    int count(TreeNode *node, long long sum, int target, unordered_map<long long, int> &seen) {
        if (node == nullptr)
            return 0;
        sum += node->val;
        int paths = seen.count(sum - target) ? seen[sum - target] : 0;
        seen[sum]++;
        paths += count(node->left, sum, target, seen);
        paths += count(node->right, sum, target, seen);
        seen[sum]--;
        return paths;
    }
};

More Binary Trees & BST problems