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);
    }
};
相关推荐
白太岁13 分钟前
Redis:(2) hiredis 使用、C++ 封装与连接池
c语言·c++·redis·缓存
Desirediscipline14 分钟前
cerr << 是C++中用于输出错误信息的标准用法
java·前端·c++·算法
Renhao-Wan28 分钟前
Java 算法实践(八):贪心算法思路
java·算法·贪心算法
汉克老师38 分钟前
GESP2024年6月认证C++二级( 第三部分编程题(2)计数 )
c++·循环结构·枚举算法·gesp二级·gesp2级·数字拆分
王老师青少年编程1 小时前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(选择题11-15)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
今儿敲了吗1 小时前
23| 画展
c++·笔记·学习·算法
Jasmine_llq1 小时前
《AT_arc081_d [ARC081F] Flip and Rectangles》
算法·动态规划(dp)·贪心思想扩展 / 收缩边界·预处理转换网格状态·二维数组遍历实现逐点计算
Desirediscipline3 小时前
#define _CRT_SECURE_NO_WARNINGS 1
开发语言·数据结构·c++·算法·c#·github·visual studio
范纹杉想快点毕业3 小时前
C语言550例编程实例说明
算法
ShineWinsu3 小时前
对于C++中map和multimap的详细介绍
c++·面试·stl·笔试·map·红黑树·multimap