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).
?
Input root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output 3
Explanation: The paths that sum to 8 are shown.
Input root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output 3
From: LeetCode
Link: 437. Path Sum III
Struct TreeNode: This is a definition for a binary tree node which contains an integer value and pointers to the left and right child nodes.
DFS Function: This recursive function takes a node and the sums targetSum and currentSum as arguments, along with a pointer to an integer count that keeps track of the number of valid paths found.
pathSumFrom Function: This function is called for each node in the tree. It uses the dfs function to explore all paths that start from the current node.
pathSum Function: This is the main function that initiates the path sum calculation. It starts the process by calling pathSumFrom for the root of the tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void dfs(struct TreeNode* node, long long targetSum, long long currentSum, int* count) {
if (!node) return;
currentSum += node->val;
if (currentSum == targetSum) {
*count += 1;
}
dfs(node->left, targetSum, currentSum, count);
dfs(node->right, targetSum, currentSum, count);
}
void pathSumFrom(struct TreeNode* node, long long targetSum, int* count) {
if (!node) return;
dfs(node, targetSum, 0, count);
pathSumFrom(node->left, targetSum, count);
pathSumFrom(node->right, targetSum, count);
}
int pathSum(struct TreeNode* root, int targetSum) {
int count = 0;
pathSumFrom(root, (long long)targetSum, &count); // Explicitly cast targetSum to long long
return count;
}