依然没想出来,思绪很乱,于是偷偷瞄了剑指offer和牛客讨论区。
发现我对递归的误解很深,总觉得这个过程有点绕,和大学的时候学递归的惯性思路一模一样,总按普通思维去思考。
主要问题就是集中在变量的生存周期。
思路:按照先序模式进行遍历,然后压入栈中,如果是叶子节点,则停下来,判断和是否为指定数字。递归会自动返回上一层,访问右节点,继续判断,直到所有的路径都被扫描完毕,结束。这点利用了每次递归参数都不会改变,所以仅仅在最后判断会加入是否是符合条件的序列。
/*
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>> all;
vector<int> a;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber){
int sum=0;
if(root==NULL) return all;
FindPath1(root,expectNumber,sum);
return all;
}
void FindPath1(TreeNode* root,int expectNumber,int sum){
if(root==NULL) return;
sum+=root->val;
a.push_back(root->val);
bool isleaf=root->right==NULL&&root->left==NULL;
if(isleaf&&sum==expectNumber){ //a是叶子,确保是一条路径,不是
all.push_back(a);
}
if(root->left) FindPath1(root->left,expectNumber,sum);
if(root->right) FindPath1(root->right,expectNumber,sum);
a.pop_back();
}
};
也可以修改成注释掉a.pop。
/*
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>> all;
vector<int> atmp;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber){
int sum=0;
if(root==NULL) return all;
FindPath1(root,expectNumber,sum,atmp);
return all;
}
void FindPath1(TreeNode* root,int expectNumber,int sum,vector<int> a){
if(root==NULL) return;
sum+=root->val;
a.push_back(root->val);
bool isleaf=root->right==NULL&&root->left==NULL;
if(isleaf&&sum==expectNumber){ //a是叶子,确保是一条路径,不是
all.push_back(a);
}
if(root->left) FindPath1(root->left,expectNumber,sum,a);
if(root->right) FindPath1(root->right,expectNumber,sum,a);
// a.pop_back();
}
};
这就是递归的神奇支出了,眼含泪水的每一天。