当前位置:网站首页>二叉树——112. 路径总和
二叉树——112. 路径总和
2022-07-25 23:55:00 【向着百万年薪努力的小赵】
1 题目描述
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
叶子节点 是指没有子节点的节点。
题目描述来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/path-sum
2 题目示例


示例 3:
输入:root = [], targetSum = 0
输出:false
解释:由于树是空的,所以不存在根节点到叶子节点的路径。
3 题目提示
树中节点的数目在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
4 思路
注意到本题的要求是,询问是否有从「根节点」到某个「叶子节点」经过的路径上的节点之和等于目标和。核心思想是对树进行一次遍历,在遍历时记录从根节点到当前节点的路径和,以防止重复计算。
需要特别注意的是,给定的 root 可能为空。
方法一:广度优先搜索
首先我们可以想到使用广度优先搜索的方式,记录从根节点到当前节点的路径和,以防止重复计算。
这样我们使用两个队列,分别存储将要遍历的节点,以及根节点到这些节点的路径和即可。
复杂度分析
- 时间复杂度:o(N),其中N是树的节点数。对每个节点访问一次。
- 空间复杂度:o(N),其中N是树的节点数。空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。
方法二:递归
观察要求我们完成的函数,我们可以归纳出它的功能:询问是否存在从当前节点root到叶子节点的路径,满足其路径和为sum。
假定从根节点到当前节点的值之和为val ,我们可以将这个大问题转化为一个小问题:是否存在从当前节点的子节点到叶子的路径,满足其路径和为sum - va1 。
不难发现这满足递归的性质,若当前节点就是叶子节点,那么我们直接判断sum是否等于va1即可(因为路径和已经确定,就是当前节点的值,我们只需要判断该路径和是否满足条件)。若当前节点不是叶子节点,我们只需要递归地询问它的子节点是否能满足条件即可。
复杂度分析
- 时间复杂度:O(N),其中N是树的节点数。对每个节点访问一次。
- 空间复杂度:O(H),其中H是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为o(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为O(log N)。
5 我的答案
方法一:广度优先搜索
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
Queue<TreeNode> queNode = new LinkedList<TreeNode>();
Queue<Integer> queVal = new LinkedList<Integer>();
queNode.offer(root);
queVal.offer(root.val);
while (!queNode.isEmpty()) {
TreeNode now = queNode.poll();
int temp = queVal.poll();
if (now.left == null && now.right == null) {
if (temp == sum) {
return true;
}
continue;
}
if (now.left != null) {
queNode.offer(now.left);
queVal.offer(now.left.val + temp);
}
if (now.right != null) {
queNode.offer(now.right);
queVal.offer(now.right.val + temp);
}
}
return false;
}
}
方法二:递归
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum == root.val;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
边栏推荐
- Redis extended data type (jump table /bitmaps/hyperloglog/geospatial)
- 静态代理+动态代理
- Getting started with Servlet
- 【ManageEngine】ServiceDesk Plus荣获2022安全样板工程数据安全奖
- Part 67: conversion between keypoint and point2f in opencv
- Scroll series
- 面试重点——传输层的TCP协议
- Static agent + dynamic agent
- 红娘的话
- Exercise (2) create a set to store the elements "1", "$", "2", "$", "3", "$", "4"“
猜你喜欢

Part 74: overview of machine learning optimization methods and superparameter settings

What is inode? It will help you understand inode and what help inode provides when creating and deleting files.

What is parity? How to use C language?

Ten threats to open API ecosystem
![[day.2] Joseph Ring problem, how to use arrays to replace circular linked lists (detailed explanation)](/img/2b/b354e52a9eb1d53475fa8d0339d33b.jpg)
[day.2] Joseph Ring problem, how to use arrays to replace circular linked lists (detailed explanation)

调用钉钉api报错:机器人发送签名过期;solution:签名生成时间和发送时间请保持在 timestampms 以内

行为型模式之观察者模式
![[learning notes] unreal 4 engine introduction (IV)](/img/30/4defa3cbd785d43adb405c71d16406.png)
[learning notes] unreal 4 engine introduction (IV)

The GUI interface of yolov3 (simple, image detection)

Leetcode 0135. distribute candy
随机推荐
SIGIR '22 recommendation system paper graph network
Leetcode 0136. numbers that appear only once: XOR
C language (high level) program environment and preprocessing
二叉树——700.二叉搜索树中的搜索
回溯——17. 电话号码的字母组合
S4/hana ME21N create Po output control message button missing solution (switch EDI output mode brf+ to Nast mode)
二叉树——404. 左叶子之和
反射之类加载过程
Dead letter queue and message TTL expiration code
结对编程实践心得
Reduce method of array
什么是奇偶校验?如何用C语言实现?
Key features and application trends of next generation terminal security management
How to solve cross domain problems
Ratio of learning_ add,ratio_ subtract,ratio_ multiply,ratio_ Use of divide
Taobao flexible.js file realizes flexible layout
Scroll case: return to top with animation
下一代终端安全管理的关键特征与应用趋势
【MUDUO】EventLoopThreadPool
Part 74: overview of machine learning optimization methods and superparameter settings