437. Path Sum III
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the number of paths in a binary tree that sum to a given targetSum. A key detail is that these paths must go downwards (from parent to child), but they do not need to start at the root or end at a leaf. This means any downward sequence of nodes forms a valid path to be considered.
Solution
Path Sum III in Python
# Definition for a binary tree node.
# 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: Optional[TreeNode], targetSum: int) -> int:
# Using instance variables to hold state during recursion.
self.count = 0
# Map to store prefix sums and their frequencies.
# Key: prefix sum, Value: frequency.
self.prefix_sum_count = {0: 1}
self.dfs(root, 0, targetSum)
return self.count
def dfs(self, node: Optional[TreeNode], current_sum: int, targetSum: int):
if not node:
return
# Update the current prefix sum.
current_sum += node.val
# Calculate the complement we are looking for.
complement = current_sum - targetSum
# Check if the complement exists in the map.
# If it does, it means there are paths ending at the current node
# which sum up to targetSum.
self.count += self.prefix_sum_count.get(complement, 0)
# Add the current prefix sum to the map for its descendant nodes.
self.prefix_sum_count[current_sum] = self.prefix_sum_count.get(current_sum, 0) + 1
# Recurse for the left and right children.
self.dfs(node.left, current_sum, targetSum)
self.dfs(node.right, current_sum, targetSum)
# Backtrack: After visiting the node and its subtree, remove its prefix sum contribution.
# This is crucial so that paths in sibling subtrees are not affected.
self.prefix_sum_count[current_sum] -= 1
Path Sum III in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// Total count of paths that sum to targetSum.
private int count = 0;
// The target sum we are looking for.
private int k;
// Map to store prefix sums and their frequencies.
// Key: prefix sum, Value: frequency.
private HashMap<Long, Integer> prefixSumCount = new HashMap<>();
public int pathSum(TreeNode root, int targetSum) {
this.k = targetSum;
// Base case: A prefix sum of 0 is available once (representing the path before the root).
// This handles paths that start from the root itself.
prefixSumCount.put(0L, 1);
dfs(root, 0L);
return count;
}
private void dfs(TreeNode node, long currentSum) {
if (node == null) {
return;
}
// Update the current prefix sum by adding the current node's value.
currentSum += node.val;
// Calculate the complement we are looking for.
long complement = currentSum - k;
// Check if the complement exists in the map.
// If it does, it means there are paths ending at the current node
// which sum up to targetSum.
count += prefixSumCount.getOrDefault(complement, 0);
// Add the current prefix sum to the map for its descendant nodes.
prefixSumCount.put(currentSum, prefixSumCount.getOrDefault(currentSum, 0) + 1);
// Recurse for the left and right children.
dfs(node.left, currentSum);
dfs(node.right, currentSum);
// Backtrack: After visiting the node and its subtree, remove its prefix sum contribution.
// This is crucial so that paths in sibling subtrees are not affected.
prefixSumCount.put(currentSum, prefixSumCount.get(currentSum) - 1);
}
}
Path Sum III in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int targetSum) {
// Map to store prefix sums and their frequencies.
// Key: prefix sum, Value: frequency.
// Using long long for prefix sum to avoid integer overflow.
std::unordered_map<long long, int> prefixSumCount;
// Base case: A prefix sum of 0 is available once (representing the path before the root).
// This handles paths that start from the root itself.
prefixSumCount[0] = 1;
int count = 0;
dfs(root, 0, targetSum, prefixSumCount, count);
return count;
}
private:
void dfs(TreeNode* node, long long currentSum, int targetSum,
std::unordered_map<long long, int>& prefixSumCount, int& count) {
if (!node) {
return;
}
// Update the current prefix sum by adding the current node's value.
currentSum += node->val;
// Calculate the complement we are looking for.
// A path from an ancestor to the current node has sum `targetSum` if
// currentSum - (prefix sum of ancestor's parent) = targetSum.
// So, we are looking for a prefix sum of `currentSum - targetSum`.
long long complement = currentSum - targetSum;
// Check if the complement exists in the map.
// If it does, it means there are paths ending at the current node
// which sum up to targetSum.
if (prefixSumCount.count(complement)) {
count += prefixSumCount[complement];
}
// Add the current prefix sum to the map to make it available for its descendant nodes.
prefixSumCount[currentSum]++;
// Recurse for the left and right children.
dfs(node->left, currentSum, targetSum, prefixSumCount, count);
dfs(node->right, currentSum, targetSum, prefixSumCount, count);
// Backtrack: After visiting the node and its subtree, remove its prefix sum contribution.
// This is crucial so that paths in sibling subtrees are not affected.
prefixSumCount[currentSum]--;
}
};
Path Sum III in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function pathSum(root: TreeNode | null, targetSum: number): number {
let count = 0;
// Map to store prefix sums and their frequencies.
// Key: prefix sum, Value: frequency.
const prefixSumCount = new Map<number, number>();
// Base case: A prefix sum of 0 is available once (representing the path before the root).
prefixSumCount.set(0, 1);
function dfs(node: TreeNode | null, currentSum: number) {
if (!node) {
return;
}
// Update the current prefix sum by adding the current node's value.
currentSum += node.val;
// Calculate the complement we are looking for.
const complement = currentSum - targetSum;
// Check if the complement exists in the map.
// If it does, it means there are paths ending at the current node
// which sum up to targetSum.
count += prefixSumCount.get(complement) || 0;
// Add the current prefix sum to the map for its descendant nodes.
prefixSumCount.set(currentSum, (prefixSumCount.get(currentSum) || 0) + 1);
// Recurse for the left and right children.
dfs(node.left, currentSum);
dfs(node.right, currentSum);
// Backtrack: After visiting the node and its subtree, remove its prefix sum contribution.
// This is crucial so that paths in sibling subtrees are not affected.
prefixSumCount.set(currentSum, prefixSumCount.get(currentSum)! - 1);
}
dfs(root, 0);
return count;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.