当前位置: 首页 > article >正文

LeetCode 112. 路径总和 II java题解

https://leetcode.cn/problems/path-sum/description/

class Solution {
    boolean res=false;//记录结果
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null) return res;
        int sum=0;
        find(root,sum,targetSum);
        return res;
    }
    public void find(TreeNode root,int sum,int target){
        if(root==null) return;
        //节点不为空。将节点值加入和
        sum+=root.val;
        //节点是叶子结点,并且和是目标和,找到结果
        if(sum==target&&root.left==null&&root.right==null){
            res=true;
            return;
        }
        //不是叶子结点
        if(root.left!=null){
            find(root.left,sum,target);
        }
        if(root.right!=null){
            find(root.right,sum,target);
        }
    }
}
/*
遍历顺序,根左右,带入和遍历下一层。
到叶子结点时,判断和,如果和=target,返回true
*/

别人的代码

class solution {
   public boolean haspathsum(treenode root, int targetsum) {
        if (root == null) {
            return false;
        }
        targetsum -= root.val;
        // 叶子结点
        if (root.left == null && root.right == null) {
            return targetsum == 0;
        }
        if (root.left != null) {
            boolean left = haspathsum(root.left, targetsum);
            if (left) {      // 已经找到
                return true;
            }
        }
        if (root.right != null) {
            boolean right = haspathsum(root.right, targetsum);
            if (right) {     // 已经找到
                return true;
            }
        }
        return false;
    }
}

// lc112 简洁方法
class solution {
    public boolean haspathsum(treenode root, int targetsum) {

        if (root == null) return false; // 为空退出

        // 叶子节点判断是否符合
        if (root.left == null && root.right == null) return root.val == targetsum;

        // 求两侧分支的路径和
        return haspathsum(root.left, targetsum - root.val) || haspathsum(root.right, targetsum - root.val);
    }
}

http://www.kler.cn/a/583709.html

相关文章:

  • 如何用Docker容器化Java应用?Spring Boot实战指南
  • Spring Boot 约定大于配置:实现自定义配置
  • HCIP复习拓扑练习(修改版)
  • 【3DGS】SuperSplat本地运行+修改监听端口+导入ply模型+修剪模型+在线渲染3DGS网站推荐
  • 设计模式C++
  • Java 8新特性:Lambda表达式与Stream API实战
  • OEM SQL Details and Session Details 5s 或者parallel 才会在sql monitor显示
  • Aliyun CTF 2025 web 复现
  • uniapp,自绘仪表盘组件(基础篇)
  • BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection 论文阅读
  • c# txt文档的实时显示,用来查看发送接收指令
  • 如何简单获取三个月免费试用的SSL证书
  • AI对前端开发的冲击
  • 第十课:项目部署与运维:从开发到生产
  • 仅仅使用pytorch来手撕transformer架构(1):位置编码的类的实现和向前传播
  • springcloud gateway搭建及动态获取nacos注册的服务信息信息
  • aws(学习笔记第三十二课) 深入使用cdk(API Gateway + event bridge)
  • C++算法学习2:二分算法精讲
  • 什么是SWIFT支付系统
  • X509TrustManager信任SSL证书