Day37: [LeetCode简单] 113. 路径总和 II
题源:
来自leetcode题库:
https://leetcode-cn.com/problems/path-sum-ii/
代码:
dirty code凑合看吧
/**
* 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 Sum;
vector<vector<int> > res;
vector<int> f(TreeNode* root,int sum){
vector<int> re;
if(root){
if(root->left==NULL&&root->right==NULL){
if(sum+root->val==Sum) {
vector<int> v;
v.push_back(root->val);
res.push_back(v);
re.push_back(res.size()-1);
return re;
}
else return re;
} else{
auto x=f(root->left,sum+root->val),y=f(root->right,sum+root->val);
for(auto i:x){
res[i].push_back(root->val);
re.push_back(i);
}
for(auto i:y){
res[i].push_back(root->val);
re.push_back(i);
}
return re;
}
}else return re;
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(!root) return res;
Sum=sum;
f(root,0);
for(int i=0;i<res.size();i++){
reverse(res[i].begin(),res[i].end());
}
//reverse(res[0].begin(),res[0].end());
return res;
}
};