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);
    }
}
相关推荐
.道阻且长.4 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC6 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Forever Nore9 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR10 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
Tisfy11 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
lucas_AI11 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法
kaixin_啊啊12 小时前
test_机器学习算法学习
学习·算法·机器学习
liulilittle12 小时前
MOE路由:路由(logits: top-k/8)
c++·人工智能·算法·机器学习·llm
旖旎夜光12 小时前
LeetCode 11:盛最多水的容器(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针