LeetCode112. Path Sum

文章目录

一、题目

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22

Output: true

Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

Input: root = [1,2,3], targetSum = 5

Output: false

Explanation: There two root-to-leaf paths in the tree:

(1 --> 2): The sum is 3.

(1 --> 3): The sum is 4.

There is no root-to-leaf path with sum = 5.

Example 3:

Input: root = [], targetSum = 0

Output: false

Explanation: Since the tree is empty, there are no root-to-leaf paths.

Constraints:

The number of nodes in the tree is in the range [0, 5000].

-1000 <= Node.val <= 1000

-1000 <= targetSum <= 1000

二、题解

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:
    bool traversal(TreeNode* root,int targetSum){
        if(root->left == nullptr && root->right == nullptr){
            return targetSum == 0;
        }
        if(root->left){
            if(traversal(root->left,targetSum-root->left->val)) return true;
        }
        if(root->right){
            if(traversal(root->right,targetSum-root->right->val)) return true;
        }
        return false;
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr) return false;
        return traversal(root,targetSum - root->val);
    }
};
相关推荐
列逍2 分钟前
深入理解 C++ 异常:从概念到实战的全面解析
开发语言·c++
AAA简单玩转程序设计18 分钟前
C++进阶小技巧:让代码从"能用"变"优雅"
前端·c++
vir0235 分钟前
密码脱落(最长回文子序列)
数据结构·c++·算法
福尔摩斯张1 小时前
二维数组详解:定义、初始化与实战
linux·开发语言·数据结构·c++·算法·排序算法
大佬,救命!!!1 小时前
C++函数式策略模式代码练习
开发语言·c++·学习笔记·学习方法·策略模式·迭代加深·多文件编译
冰西瓜6001 小时前
模与内积(五)矩阵分析与应用 国科大
线性代数·算法·矩阵
Samuel-Gyx1 小时前
数据结构--二叉树构造与遍历顺序的相互转化
数据结构
努力学算法的蒟蒻1 小时前
day17(11.18)——leetcode面试经典150
算法·leetcode·面试
缘友一世1 小时前
模型微调DPO算法原理深入学习和理解
算法·模型微调·dpo
未若君雅裁1 小时前
斐波那契数列 - 动态规划实现 详解笔记
java·数据结构·笔记·算法·动态规划·代理模式