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

算法思想

运行结果


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

相关推荐
文丑颜不良啊12 小时前
LeetCode3041~3060题目解析
java·leetcode
eggwyw12 小时前
C++ union 的一种妙用法
开发语言·c++
罗西的思考12 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊13 小时前
LeetCode3101~3120题目解析
java·leetcode
ShineWinsu13 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步14 小时前
string的实现(1)
c++·笔记·visual studio
kyle~16 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
敲上瘾17 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
老花眼猫17 小时前
C语言绘图方法:(10)椭圆缩放旋转
c语言·经验分享·青少年编程·课程设计
牢姐与蒯18 小时前
cpp算法之哈希
c++·算法·哈希算法