Leetcode—112.路径总和【简单】

2023每日刷题(五十七)

Leetcode---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:
    bool dfs(TreeNode* root, int sum) {
        if(root == nullptr) {
            return false;
        }
        if(root->left == nullptr && root->right == nullptr) {
            return sum == root->val;
        }
        return dfs(root->left, sum - root->val) || dfs(root->right, sum - root->val);
    }

    bool hasPathSum(TreeNode* root, int targetSum) {
        return dfs(root, targetSum);
    }
};

算法思想

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
Raink老师15 小时前
用100道题拿下你的算法面试(链表篇-4):合并 K 个有序链表
算法·链表·面试
宝宝单机sop16 小时前
事业单位考试合集
经验分享
captain_AIouo16 小时前
Captain AI以数据为核心,打造OZON智能决策引擎
大数据·人工智能·经验分享·aigc
Liangwei Lin16 小时前
LeetCode 20. 有效的括号
算法
艾莉丝努力练剑16 小时前
【Linux网络】Linux 网络编程入门:TCP Socket 编程(下)
linux·运维·服务器·网络·c++·tcp/ip
宵时待雨16 小时前
linux笔记归纳4:进程概念
linux·运维·服务器·c++·笔记
IronMurphy16 小时前
【算法四十四】322. 零钱兑换
算法
凯瑟琳.奥古斯特16 小时前
力扣2760 C++滑动窗口解法
数据结构·c++·算法·leetcode·职场和发展
Hesionberger16 小时前
LeetCode96: 不同的二叉搜索树(多解)
算法
_深海凉_16 小时前
LeetCode热题100-不同路径
算法·leetcode·职场和发展