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);
    }
}
相关推荐
一一Null1 小时前
Android studio 动态布局
android·java·android studio
假女吖☌1 小时前
Maven 编译指定模版
java·开发语言·maven
Wils0nEdwards2 小时前
Leetcode 独一无二的出现次数
算法·leetcode·职场和发展
Y.O.U..2 小时前
力扣HOT100——无重复字符的最长子字符串
数据结构·c++·算法·leetcode
CodeJourney.2 小时前
从PPT到DeepSeek开启信息可视化的全新之旅
数据库·人工智能·算法·excel·流程图
体育分享_大眼3 小时前
从零搭建高并发体育直播网站:架构设计、核心技术与性能优化实战
java·性能优化·系统架构
琢磨先生David4 小时前
Java 在人工智能领域的突围:从企业级架构到边缘计算的技术革新
java·人工智能·架构
Ludicrouers4 小时前
【Leetcode-Hot100】和为k的子数组
算法·leetcode·职场和发展
巨可爱熊4 小时前
高并发内存池(定长内存池基础)
linux·运维·服务器·c++·算法
计算机学姐4 小时前
基于SpringBoo的地方美食分享网站
java·vue.js·mysql·tomcat·mybatis·springboot·美食