您的位置:首页 > 其它

437. Path Sum III

2018-01-01 16:03 441 查看




curSum代表从root到当前节点所累加和,res表示有多少路径符合要求,out中保存从根节点到当前节点所经过的路径。

int pathSum(TreeNode* root, int sum) {
int res=0;
vector<TreeNode*> out;
helper(root,sum,0,out,res);
return res;
}

void helper(TreeNode* root,int sum,int curSum,vector<TreeNode*>& out,int& res){
if(!root) return ;
curSum+=root->val;
out.push_back(root);
if(curSum==sum) res++;
int t=curSum;
for(int i=0;i<out.size()-1;++i){
t-=out[i]->val;
if(t==sum)
res++;
}
helper(root->left,sum,curSum,out,res);
helper(root->right,sum,curSum,out,res);
out.pop_back();
}


int pathSum(TreeNode* root, int sum) {
unordered_map<int,int>m;
m[0]=1;
return helper(root,sum,0,m);
}
int helper(TreeNode* root,int sum,int curSum,unordered_map<int,int>& m){
if(!root) return 0;
curSum+=root->val;
int res=m[curSum-sum];
++m[curSum];
res+=helper(root->left,sum,curSum,m)+helper(root->right,sum,curSum,m);
--m[curSum];
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: