You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
- 5 -> 3
- 5 -> 2 -> 1
- -3 -> 11
思路:还是对每个节点为起始点向下开始考虑。递归函数向下传递三个参数,分别的左或右节点,迄今为止加起来有多少值,和用来比较的sum值。返回的是当前节点相等的话就加一个1以及往下再数有多少相等节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(root==NULL) return 0;
return sumup(root,0,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
}
int sumup(TreeNode* root,int res,int& sum)
{
if(root==NULL) return 0;
int ch=res+root->val;
return (ch==sum)+sumup(root->left,ch,sum)+sumup(root->right,ch,sum);
}
};
下面是我二刷时的代码,主要的思路跟上面一样,但是我不太适应那么多的递归,主要是主函数递归太难设置返回值了。所以我自己多写了一个函数,让主函数去调用这个递归函数。
应该注意,这里的起始和终止不一定是根节点和叶结点,所以不能直接dfs。但是可以这样,就是不断地让每一个节点作为根节点去考虑,也就是下面地fullsearch函数,这样就是相当于子树调用dfs搜索。所以就是三个函数。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int count=0;
int pathSum(TreeNode* root,int sum) {
if(!root) return 0;
fullsearch(root,sum);
return count;
}
void fullsearch(TreeNode* root,int sum)
{
dfs(root,0,sum);
if(root->left)
fullsearch(root->left,sum);
if(root->right)
fullsearch(root->right,sum);
}
void dfs(TreeNode* root,int tempsum ,int target){
tempsum+=root->val;
if(target==tempsum) count++;
if(root->left) dfs(root->left,tempsum,target);
if(root->right) dfs(root->right,tempsum,target);
}
};
三刷时,发现有一些地方要注意
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int result=0;
int pathSum(TreeNode* root, int sum) {
if(!root) return result;
searchpath(root,sum);
return result;
}
void searchpath(TreeNode* root,int sum){
if(!root) return ;
dfs(root,0,sum);
if(root->left) searchpath(root->left,sum);
if(root->right) searchpath(root->right,sum);
return ;
}
void dfs(TreeNode* root,int res,int sum){
if(!root) return ;
res+=root->val;//这一句在前面,否则没有考虑最底下的叶结点到res里面
if(res==sum){
result+=1;
//return ;不能有这一句,否则相等了以后,可能后面还有 -1 1 节点相加为零的情况没有考虑进去
}
if(root->left) dfs(root->left,res,sum);
if(root->right) dfs(root->right,res,sum);
}
};