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);
    }
}
相关推荐
民乐团扒谱机3 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T3 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
wy_hhxx4 小时前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者4 小时前
每天10分钟学Go:第20课 泛型
c++·算法·golang
AIgorithmGEEK6 小时前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
风落青芜8 小时前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z9 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah9 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
草履虫AI课10 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习
AAA修煤气灶刘哥10 小时前
明明输入了完整报错,知识库怎么净给我相似答案?
人工智能·后端·算法