Leetcode 112. 路径总和

题目链接:https://leetcode.cn/problems/path-sum/description/

思路

  • 递归,先序遍历二叉树,每遍历一个节点便减去当前存储值(targetSum = targetSum - root.val);
  • 当到达某个节点等于targetSum (targetSum == root.val),判断该节点是否为叶子节点(root.left == null && root.right == null),如果是那么返回true;
  • 如果该节点不满足targetSum,那么递归遍历左子树和右子树(hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum - root.val)),任意一个返回true就成功。

代码实现

java 复制代码
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null){ //空节点
            return false;
        }
        if(root.left == null && root.right == null){ // 该节点为叶子节点
            return targetSum == root.val; //相等则为true
        }
        return hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum - root.val);
    }
}
相关推荐
Dola_Zou3 小时前
工厂智能排产软件算法保护与按产线计费实战
算法·自动化·软件工程·软件加密
啦啦啦啦啦zzzz5 小时前
Logger的组装(c++20)
c++·算法·c++20
尾善爱看海6 小时前
前端算法与手写题集
前端·算法
程序员阿鹏6 小时前
为什么MySQL InnoDB选择B+树?
数据结构·数据库·b树·sql·mysql·算法·缓存
AI 思录7 小时前
Prompt 事故档案(八):日常表达被标为“待校准”,AI 的爹味语法从哪里来
大数据·人工智能·算法·prompt·用户体验·ai合规
月光船幽幽7 小时前
跨范式映射的稳定接口设计
人工智能·python·算法
2601_965742228 小时前
全媒体运营与短视频代运营,两者有什么区别?
大数据·数据结构·人工智能·算法·ai·媒体
wordbaby9 小时前
混合检索:两全其美的艺术
人工智能·算法
彧azz9 小时前
数据结构:关于图的学习
c语言·数据结构·笔记·学习·算法