不要用下标访问没有给定初始大小的vector
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int>> path;
vector<int> tempPath;
int number = 0;
void dfs(TreeNode* v, int target){
tempPath.push_back(v->val);
if(v->left == NULL && v->right == NULL){
int sum = 0;
for(int i = 0; i < tempPath.size(); ++i){
sum += tempPath[i];
}
if(sum == target){
path.push_back(tempPath);
}
tempPath.pop_back();
return;
}
if(v->left != NULL) dfs(v->left,target);
if(v->right != NULL) dfs(v->right,target);
tempPath.pop_back();//当一个结点的左右结点都遍历完了,就弹出自身
return;
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root == NULL) return path;
dfs(root,expectNumber);
return path;
}
};