LeetCode 112. 路径总和 II java题解

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

java 复制代码
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
*/

别人的代码

java 复制代码
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);
    }
}
相关推荐
karry_k3 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k3 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
vibecoding日记5 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21387 小时前
Verilog参数化游程编码RLE模块
算法
SamDeepThinking7 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
望易7 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
她的男孩10 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
复杂网络11 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
荣码11 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python