LeetCode113. 路径总和 II

在这里插入图片描述


LeetCode113. 路径总和 II


题目:

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

示例:

在这里插入图片描述

  • 输入: r o o t = [ 5 , 4 , 8 , 11 , n u l l , 13 , 4 , 7 , 2 , n u l l , n u l l , 5 , 1 ] , t a r g e t S u m = 22 root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 root=[5,4,8,11,null,13,4,7,2,null,null,5,1],targetSum=22
  • 输出: [ [ 5 , 4 , 11 , 2 ] , [ 5 , 8 , 4 , 5 ] ] [[5,4,11,2],[5,8,4,5]] [[5,4,11,2],[5,8,4,5]]

解题思路一:(递归)

  1. 确定递归函数的参数和返回值:
vector<vector<int>> res;
vector<int> path;
void dfs(TreeNode* cur, int cnt)
  1. 确定终止条件:
if(!cur->left && !cur->right && cnt == 0){
    res.push_back(path);
    return;
} 
if(!cur->left && !cur->right) return;
  1. 确定单层递归逻辑: 先序遍历顺序为: 左 − > 中 − > 右 左->中->右 >>
if(cur->left){
    cnt -= cur->left->val;
    path.push_back(cur->left->val);
    dfs(cur->left, cnt);
    cnt += cur->left->val;
    path.pop_back();
}
if(cur->right){
    cnt -= cur->right->val;
    path.push_back(cur->right->val);
    dfs(cur->right, cnt);
    cnt += cur->right->val;
    path.pop_back();
}
return;

C++版整体代码

class Solution {
public:
    vector<vector<int>> res;
    vector<int> path;
    void dfs(TreeNode* cur, int cnt){
        if(!cur->left && !cur->right && cnt == 0){
            res.push_back(path);
            return;
        } 
        if(!cur->left && !cur->right) return;
        if(cur->left){
            cnt -= cur->left->val;
            path.push_back(cur->left->val);
            dfs(cur->left, cnt);
            cnt += cur->left->val;
            path.pop_back();
        }
        if(cur->right){
            cnt -= cur->right->val;
            path.push_back(cur->right->val);
            dfs(cur->right, cnt);
            cnt += cur->right->val;
            path.pop_back();
        }
        return;
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        res.clear(), path.clear();
        if(root == NULL) return res;
        path.push_back(root->val);
        dfs(root, targetSum - root->val);
        return res;
    }
};
  • 26
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值