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; }
相关文章推荐
- LeetCode 437 Path Sum III
- LeetCode "437. Path Sum III"
- LeetCode 437 Path Sum III 题解
- 437. Path Sum III
- leetcode(437):Path Sum III
- 437. Path Sum III
- leetcode-437-Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- [437]. Path Sum III,[687]. Longest Univalue Path
- 437. Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- 437. Path Sum III
- LeetCode.112(113/437) Path Sum I && II && III
- 437. Path Sum III
- 437. Path Sum III
- 437. Path Sum III