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);
    }
}
相关推荐
夏末秋也凉26 分钟前
力扣-回溯-491 非递减子序列
数据结构·算法·leetcode
penguin_bark28 分钟前
三、动规_子数组系列
算法·leetcode
kyle~37 分钟前
thread---基本使用和常见错误
开发语言·c++·算法
曲奇是块小饼干_1 小时前
leetcode刷题记录(一百零八)——322. 零钱兑换
java·算法·leetcode·职场和发展
小wanga1 小时前
【leetcode】滑动窗口
算法·leetcode·职场和发展
少年芒1 小时前
Leetcode 490 迷宫
android·算法·leetcode
BingLin-Liu2 小时前
蓝桥杯备考:搜索算法之枚举子集
算法·蓝桥杯·深度优先
码农诗人2 小时前
调用openssl实现加解密算法
算法·openssl·ecdh算法
IT猿手2 小时前
2025最新智能优化算法:鲸鱼迁徙算法(Whale Migration Algorithm,WMA)求解23个经典函数测试集,MATLAB
android·数据库·人工智能·算法·机器学习·matlab·无人机
别NULL2 小时前
机试题——编辑器
c++·算法