思路:
从该结点开始计算sum
从该节点开始继承之前的sum
重复很多枝,会从一个结点重复开始很多次,需要剪枝
class Solution {
public:
int cnt = 0;
int sum1 = 0;
int pathSum(TreeNode* root, int sum) {
this->sum1 = sum;
findw( root,sum );
return cnt;
}
void findw( TreeNode* root, int sum ){
if( root == nullptr ){
return ;
}else if( sum-root->val == 0 && root->left == nullptr && root->right == nullptr){
cnt ++;
return ;
}else if( sum-root->val == 0){
cnt++;
}
if( root->left != nullptr ){
findw( root->left,sum - root->val );
findw( root->left,sum1 );
}
if( root->right != nullptr){
findw( root->right,sum - root->val );
findw( root->right,sum1 );
}
}
};
用两重递归,规定只从一个结点开始,定住开始的结点,避免重复
class Solution {
public:
int cnt = 0;
int sum1 = 0;
int pathSum(TreeNode* root, int sum) {
if (root == nullptr) {
return 0;
}
return paths(root, sum)
+ pathSum(root->left, sum)
+ pathSum(root->right, sum);
}
int paths( TreeNode* root, int sum ){
if (root == nullptr) {
return 0;
}
int res = 0;
if (root->val == sum) {
res += 1;
}
res += paths(root->left, sum - root->val);
res += paths(root->right, sum - root->val);
return res;
}
};
class Solution {
public:
int ssum = 0;
int ret = 0;
map<int,int>mp;
int pathSum(TreeNode* root, int sum) {
ssum = sum;
mp[0] = 1;
findw( root,0 );
return ret;
}
void findw(TreeNode* root,int cur){
if(root!=nullptr){
if( mp[ cur+root->val - ssum] >= 1 ){
ret += mp[ cur+root->val - ssum];
}
mp[cur+root->val] += 1;
findw( root->left,cur+root->val );
findw( root->right,cur+root->val );
mp[cur+root->val] -= 1;
}
}
};
空间耗费挺大的,可能是因为map
标签:return,val,int,root,sum,findw,437,III,leetcode From: https://blog.51cto.com/liyunhao/6077020