leetcode0113. 路径总和 II - medium

1 题目:路径总和 II

官方标定难度:中

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

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

示例 1:

输入:root = 5,4,8,11,null,13,4,7,2,null,null,5,1, targetSum = 22

输出:\[5,4,11,2,5,8,4,5]

示例 2:

输入:root = 1,2,3, targetSum = 5

输出:\[\]

示例 3:

输入:root = 1,2, targetSum = 0

输出:\[\]

提示:

树中节点总数在范围 0, 5000

-1000 <= Node.val <= 1000

-1000 <= targetSum <= 1000

2 solution

和 112 题差不多,只不过需要保存路径,只需要,在每一步时,将当前节点加入到路径中,如果找到一个答案,就保存下来。

代码

cpp 复制代码
/**
 * 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 pathSum(TreeNode *root, int targetSum, vector<vector<int>> &result,
             vector<int> &solution) {
    if (!root->left && !root->right) {
        if (targetSum == root->val) {
            solution.push_back(root->val);
            result.push_back(solution);
            solution.pop_back();
        }
        return;
    }

    solution.push_back(root->val);
    targetSum -= root->val;
    if (root->left) pathSum(root->left, targetSum, result,solution);
    if (root->right) pathSum(root->right, targetSum, result,solution);
    solution.pop_back();
}

vector<vector<int>> pathSum(TreeNode *root, int targetSum) {
    if (!root) return {};
    vector<vector<int>> result;
    vector<int> solution;
    pathSum(root, targetSum, result,solution);
    return result;
}

};

结果

相关推荐
郝学胜-神的一滴几秒前
Qt 高级编程 045:坐标体系深度实战
开发语言·c++·windows·python·qt·程序人生
码匠许师傅10 分钟前
【设计模式精讲】22.中介者模式(Mediator)
c++·设计模式·软件工程·uml·中介者模式
a187927218311 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
2601_962297481 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
辰烨chenye2 小时前
LeetCode Hot 100 题解 · 子串篇
算法·leetcode·职场和发展
辰烨chenye2 小时前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
手写码匠2 小时前
华为云Flexus+DeepSeek征文|DeepSeek 应用监控告警体系实战:从“用户投诉才知道“到“故障前就发现“
人工智能·深度学习·算法·aigc
shehuiyuelaiyuehao3 小时前
算法29,前缀和,除自身以外的数组的乘积
java·数据结构·算法
智购科技自动售货机厂家3 小时前
2026自动售货机设备清洁效果自动验证:从图像比对到评分算法的工程实践~YH
人工智能·算法·计算机视觉
爱吃巧克力的程序媛3 小时前
main.cpp注册 C++ 类到 QML 元对象系统
c++·qt