当前位置:网站首页>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);
}
}
边栏推荐
- 二叉树——222. 完全二叉树的节点个数
- Seventy second: pedestrian detection
- C language actual combat guessing game
- JS synchronization and asynchrony
- Yolov3 trains its own data set
- 二叉树——654. 最大二叉树
- The GUI interface of yolov3 (simple, image detection)
- NVIDIA cuDNN学习
- SIGIR '22 recommendation system paper graph network
- 通货膨胀之下,后市如何操作?2021-05-14
猜你喜欢

Stm32 systeminit trap during simulation debugging

TOPSIS and entropy weight method

Dead letter queue and message TTL expiration code

The process of finding free screen recording software - I didn't expect win10 to come with this function

老旧笔记本电脑变服务器(笔记本电脑+内网穿透)

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

Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK

Ten threats to open API ecosystem

二叉树——700.二叉搜索树中的搜索

Vscode format JSON file
随机推荐
老旧笔记本电脑变服务器(笔记本电脑+内网穿透)
Pytoch learning record (I): introduction to pytoch
[one library] mapbox GL! A map engine out of the box
Sort fake contacts
什么是奇偶校验?如何用C语言实现?
QT smart pointer error prone point
The GUI interface of yolov3 (simple, image detection)
What is parity? How to use C language?
二叉树——104. 二叉树的最大深度
BOM 浏览器对象模型
牛市还没有结束,还有下半场 2021-05-18
Key features and application trends of next generation terminal security management
Compile live555 with vs2019 in win10
Typescript TS basic knowledge and so on
BGR and RGB convert each other
行为型模式之责任链模式
NVIDIA可编程推理加速器TensorRT学习笔记(三)——加速推理
Key and difficult points of C language pointer
STM32 serial port
Getting started with Servlet