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);
    }
}
相关推荐
玖玥拾2 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
数据皮皮侠AI2 小时前
上市公司数字供应链金融指数(2010-2024)
大数据·人工智能·算法
Hi李耶3 小时前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
shylyly_3 小时前
104.二叉树的最大深度
数据结构·算法·104.二叉树的最大深度
AI科技星3 小时前
曲率‑挠率与 $\boldsymbol{\omega/c}$ 的关系、精算验证及其物理意义
c语言·开发语言·线性代数·算法·决策树·机器学习·ai科技星
沐籽李4 小时前
HuDiff在抗体人源化项目中的工程化落地
人工智能·算法·aidd·抗体设计
依然范特东4 小时前
强化学习笔记6--IS、PPO、TD、DQN、Actor-Critic
笔记·算法
一次旅行6 小时前
RLHF全链路深度解析:Reward Model数学推导+PPO完整实战,对比GRPO轻量化方案
人工智能·算法·机器学习
Wang's Blog6 小时前
AI Agent白手起家29: Few Shot 提示词工程实战
人工智能·算法
June`6 小时前
warp shuffle指令
c++·人工智能·算法·cuda