当前位置:网站首页>Binary tree - 112. Path sum
Binary tree - 112. Path sum
2022-07-26 00:04:00 【Xiao Zhao, who is working hard for millions of annual salary】
1 Title Description
Give you the root node of the binary tree root And an integer representing the sum of goals targetSum . Determine if there is Root node to leaf node The path of , The sum of the values of all nodes in this path is equal to the target and targetSum . If there is , return true ; otherwise , return false .
Leaf node A node without children .
Title Description source : Power button (LeetCode)
link :https://leetcode.cn/problems/path-sum
2 Title Example


Example 3:
Input :root = [], targetSum = 0
Output :false
explain : Because the tree is empty , Therefore, there is no path from root node to leaf node .
3 Topic tips
The number of nodes in the tree is in the range [0, 5000] Inside
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
4 Ideas
Notice that the requirement of this question is , Ask if there is from 「 The root node 」 To a certain 「 Leaf node 」 The sum of nodes on the path is equal to the target sum . The core idea is to traverse the tree once , When traversing, record the path and path from the root node to the current node , To prevent double counting .
Here's the thing to watch out for , A given root May is empty .
Method 1 : Breadth first search
First of all, we can think of using breadth first search , Record the path and path from the root node to the current node , To prevent double counting .
So we use two queues , Store the nodes to be traversed separately , And the path and from the root node to these nodes .
Complexity analysis
- Time complexity :o(N), among N Is the number of nodes in the tree . Access once for each node .
- Spatial complexity :o(N), among N Is the number of nodes in the tree . The space complexity mainly depends on the overhead of the queue , The number of elements in the queue will not exceed the number of nodes in the tree .
Method 2 : recursive
Look at the function that we are asked to complete , We can sum up its functions : Ask if there is a from the current node root The path to the leaf node , Satisfy its path and sum.
Assume that the sum of the values from the root node to the current node is val , We can turn this big problem into a small problem : Whether there is a path from the child node of the current node to the leaf , Satisfy its path and sum - va1 .
It is not difficult to find that this satisfies the nature of recursion , If the current node is a leaf node , So let's judge directly sum Is it equal to va1 that will do ( Because the path and have been determined , Is the value of the current node , We just need to judge whether the path and meet the conditions ). If the current node is not a leaf node , We just need to recursively ask whether its child nodes can meet the conditions .
Complexity analysis
- Time complexity :O(N), among N Is the number of nodes in the tree . Access once for each node .
- Spatial complexity :O(H), among H Is the height of the tree . The space complexity mainly depends on the overhead of stack space during recursion , In the worst case , The trees are in chains , The space complexity is o(N). On average, the height of the tree is positively correlated with the logarithm of the number of nodes , The space complexity is O(log N).
5 My answer
Method 1 : Breadth first search
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;
}
}
Method 2 : recursive
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);
}
}
边栏推荐
- STM32 pit encountered when using timer to do delay function
- 抽丝剥茧C语言(高阶)程序环境和预处理
- After entering www.baidu.com in the address bar
- Pyqt5 rapid development and actual combat.pdf sharing
- 什么叫做 inode ?带你理解 inode 和对于创建文件和删除文件时 inode 都提供了哪些帮助。
- 行为型模式之责任链模式
- Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
- 死信队列 和消息TTL过期代码
- Iterator pattern of behavioral pattern
- YoloV4-tiny网络结构
猜你喜欢

Responsibility chain model of behavioral model

本轮牛市还能持续多久?|疑问解答 2021-05-11

SHIB(柴犬币)一月涨幅数百倍,百倍币需具备哪些核心要素?2021-05-09

Key features and application trends of next generation terminal security management

栈与队列——239. 滑动窗口最大值

C - readonly and const keywords

Stm32 systeminit trap during simulation debugging

BOM browser object model

Sort fake contacts

二叉树——404. 左叶子之和
随机推荐
STM32 pit encountered when using timer to do delay function
Shardingsphere data slicing
Song of statistics lyrics
Nacos offline service times error errcode: 500
Android solves the risk of database injection vulnerability
“群魔乱舞”,牛市是不是结束了?2021-05-13
抽丝剥茧C语言(高阶)程序环境和预处理
Weight file and pre training file of yolov3
Article 75: writing skills of academic papers
二叉树——101. 对称二叉树
SQLZOO——Nobel Quiz
Responsibility chain model of behavioral model
【一库】mapbox-gl!一款开箱即用的地图引擎
C# - readonly 和 const 关键字
Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
Part 66: monocular 3D reconstruction point cloud
Leetcode question brushing series -- 931. Minimum sum of descent path
通货膨胀之下,后市如何操作?2021-05-14
JS synchronization and asynchrony
【ManageEngine】ServiceDesk Plus荣获2022安全样板工程数据安全奖