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;
}

};

结果

相关推荐
虾球xz5 分钟前
CppCon 2015 学习:CLANG/C2 for Windows
开发语言·c++·windows·学习
laocui129 分钟前
Σ∆ 数字滤波
人工智能·算法
CodeWithMe42 分钟前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
yzx99101344 分钟前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥1 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥1 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu1 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Humbunklung2 小时前
机器学习算法分类
算法·机器学习·分类
Ai多利2 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
lyh13442 小时前
【SpringBoot自动化部署方法】
数据结构