113二叉树的路径综合2

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:本题与112题极其相似只需要在递归终止的时候增加两个数组来将符合条件的值装入数组中其他逻辑相同。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void travsal(TreeNode* root,int count,vector<int>&path,vector<vector<int>>&res)
    {
        if(!root->left&&!root->right&&count==0)
        {
            res.push_back(path);
            return ;
        }//递归终止条件的判断
        if(!root->left&&!root->right) return;//递归终止条件
        if(root->left){
            count-=root->left->val;
            path.push_back(root->left->val);
            travsal(root->left,count,path,res);//递归
            count+=root->left->val;//回溯
            path.pop_back();//回溯
        }
        if(root->right){
            count-=root->right->val;
            path.push_back(root->right->val);
            travsal(root->right,count,path,res);//递归
            count+=root->right->val;//回溯
            path.pop_back();//回溯 
        }
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<int>path;
        vector<vector<int>>result;
        path.clear();
        result.clear();
        if(root==NULL) return result;
        path.push_back(root->val);
        travsal(root,targetSum-root->val,path,result);
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值