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);
    }
}
相关推荐
HDU-Dade26 分钟前
【校招笔试真题】简要介绍 Self-Attention 的前沿算法
人工智能·算法
Xin7701 小时前
LeetCode 79. 单词搜索(DFS 回溯法)
leetcode
小郎君6583 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
邵奈一3 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS1003 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法
shehuiyuelaiyuehao3 小时前
算法56,重排链表
数据结构·算法·链表
qq_452396234 小时前
第四篇:《索引原理与实战:B-tree、Hash、GIN、GiST、BRIN》
算法·哈希算法·gin
西索斯coding4 小时前
Qwen3-Max 与 Qwen-Plus:60 个真实修复任务评测方案
大数据·网络·算法·ai
INGNIGHT5 小时前
440 · 背包问题(三)(无限次数)
算法·leetcode·动态规划