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);
    }
}
相关推荐
HjhIron12 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩14 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹15 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术19 小时前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望21 小时前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰21 小时前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者1 天前
J6B vio scenario sample
算法
BothSavage2 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn2 天前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法