二叉树中和为某一值的路径

依然没想出来,思绪很乱,于是偷偷瞄了剑指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();

    }
};

这就是递归的神奇支出了,眼含泪水的每一天。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值