Given the root
of a binary tree and an integer targetSum
, return the number of paths where the sum of the values along the path equals targetSum
. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
10^4
nodes can be expected.The problem can be seen as finding all paths in the tree such that the sum of nodes in the path equals targetSum
. We’ll use two main strategies to solve this problem:
The key idea with the prefix sum approach is:
#include <iostream>
#include <unordered_map>
using namespace std;
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) {
unordered_map<long, int> prefixSumMap;
prefixSumMap[0] = 1; // Base case: a path sum equal to the targetSum itself.
return dfs(root, 0, targetSum, prefixSumMap);
}
private:
int dfs(TreeNode* node, long currentSum, int targetSum, unordered_map<long, int>& prefixSumMap) {
if (!node) return 0;
currentSum += node->val;
int numPathsToCurr = prefixSumMap[currentSum - targetSum];
prefixSumMap[currentSum]++;
int numPathsInLeftSubtree = dfs(node->left, currentSum, targetSum, prefixSumMap);
int numPathsInRightSubtree = dfs(node->right, currentSum, targetSum, prefixSumMap);
prefixSumMap[currentSum]--;
return numPathsToCurr + numPathsInLeftSubtree + numPathsInRightSubtree;
}
};
Time Complexity: The time complexity is (O(N)), where (N) is the number of nodes in the tree. This is because each node is visited once, and prefix sum operations are (O(1)).
Space Complexity: The space complexity is (O(H)) for the recursion stack, where (H) is the height of the tree, plus the space required for the prefix sum hashmap. In the worst case, the height of the tree could be (N), resulting in (O(N)) space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?