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);
    }
}
相关推荐
小溪学编程12 分钟前
Java InputStream 详解:从基础到实战
java·python·php
血小板要健康12 分钟前
队列 + 宽搜(BFS):二叉树层序遍历 算法总结
java·数据结构·笔记·算法·leetcode·宽度优先
Felven17 分钟前
A. Riptide
算法·c 算法
m0_7393128724 分钟前
四元数、李群SO(3)/李代数so(3)的作用及应用场景
算法·机器人·自动驾驶
A黄俊辉A38 分钟前
【无标题】
java
BestHeaker42 分钟前
跨企业接口对接:IQDS / CPK 数据解析与协作避坑指南(五)
java·服务器·前端
artificiali1 小时前
880 第4章多元
人工智能·算法
Felven1 小时前
B. Deja Vu
数据结构·算法
俊昭喜喜里1 小时前
C#中的func<>
java·前端·c#
highreport1 小时前
net报表工具对比:HighReport 与 FastReport
java·c#