/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
#include <numeric>
class Solution {
public:
//test
vector<vector<int>> results; 用来保存每一条路径的元素
vector<int> result;
void findsum(TreeNode* root){
if(root == nullptr){
return;
}else{
/*先序插入 (一定是根据路径插入)*/
result.push_back(root->val);
if(root->left == nullptr && root->right == nullptr){
results.push_back(result);
}
findsum(root->left);
findsum(root->right);
/*下面这行是核心,一定要理解递归*/
/*后序删除,一个路径遍历完毕开始回溯,下一行删除当前路径尾部节点*/
result.pop_back();
/*实在搞不懂就记住吧,这个方法可以check到所有的路径*/
}
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
findsum(root); vector<vector<int>> res;
for(int i = 0;i<results.size();i++){
//对每个vector<int> 求和
int sum = accumulate(results[i].begin(),results[i].end(),0);
cout << sum <<",";
if(sum == expectNumber){
res.push_back(results[i]);
}
}
return res;
}
};