当前位置:网站首页>Leetcode-112:路径总和
Leetcode-112:路径总和
2022-07-03 09:22:00 【ITSOK_U】
112. 路径总和
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。
如果存在,返回 true ;否则,返回 false 。叶子节点是指没有子节点的节点。
这道题和题257. 二叉树的所有路径十分类似,代码也相似。
深度优先(O(N),O(N))
在本题使用深度优先的话可以使用前序递归来模拟实现,但是在递归中需要处理的是每个节点的路径和的计算要确保不对其它的节点路径和计算造成影响,所以使用递归的话在其回溯过程会需要处理那些多余的叶节点。
如在上述的路径和计算中,第一条叶子节点的路径和计算为1+2+4,如果此时不满足要求,则需要进行回溯,所以要更新已有结果为1+2,使用递归的话可以完美的解决这种问题,如下面代码中的return就可以实现有效的回溯。
if(root->left == nullptr && root->right == nullptr){
if(num == target) falg = true;
// 否则继续递归
return;
}
具体解题代码如下:
class Solution {
public:
void findPath(TreeNode* root,int num,int target,bool &falg){
// 新加入了节点更新路径和
num += root->val;
// 到达叶子节点
if(root->left == nullptr && root->right == nullptr){
// 满足求解条件,结果标志为真
if(num == target){
falg = true;
}
// 否则继续递归
return;
}
// 左子树递归
if(root->left) findPath(root->left,num,target,falg);
// 右子树递归
if(root->right) findPath(root->right,num,target,falg);
}
bool hasPathSum(TreeNode* root, int targetSum) {
// 根节点为空,返回false
if(root == nullptr) return false;
// falg用来标记求解结果
bool falg = false;
findPath(root,0,targetSum,falg);
return falg;
}
};
广度优先(O(N),O(N))
使用广度优先的话就是模拟一次层序遍历。不过相比于普通的打印路径之类的求解,此时我们需要维护一个各个节点已有的路径和队列。如下图所示。我们的路径和队列是和树节点队列一一位置对应的,也就是说,与树节点队列相同位置的路径和队列的值就是到该树节点的路径和。
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
// 空树直接返回false
if(root == nullptr) return false;
// 初始化广度遍历的树节点队列
queue<TreeNode*> que;
queue<int> num;
que.push(root);
num.push(root->val);
// 队列不为空则节点未处理完
while(!que.empty()){
// 取出树节点队列以及路径和队列的首元素
TreeNode* node = que.front();
int res=num.front();
que.pop();
num.pop();
// 如果到了叶子节点而且路径和满足要求则直接跳出遍历,返回true
if(node->left==nullptr && node->right==nullptr && res==targetSum)
return true;
if(node->left){
que.push(node->left);
// 下一层节点入队,并将其对应的节点路径和存储
num.push(node->left->val + res);
}
if(node->right){
que.push(node->right);
// 下一层节点入队,并将其对应的节点路径和存储
num.push(node->right->val + res);
}
}
// 节点处理完仍然没有找到加和为targetSum的路径,返回false
return false;
}
};
边栏推荐
- LeetCode - 508. 出现次数最多的子树元素和 (二叉树的遍历)
- LeetCode - 1670 設計前中後隊列(設計 - 兩個雙端隊列)
- Working mode of 80C51 Serial Port
- Interruption system of 51 single chip microcomputer
- Adaptiveavgpool1d internal implementation
- LeetCode - 705 设计哈希集合(设计)
- CV learning notes - feature extraction
- Retinaface: single stage dense face localization in the wild
- 4G module designed by charging pile obtains signal strength and quality
- openEuler kernel 技术分享 - 第1期 - kdump 基本原理、使用及案例介绍
猜你喜欢

Open Euler Kernel Technology Sharing - Issue 1 - kdump Basic Principles, use and Case Introduction

2.Elment Ui 日期选择器 格式化问题

使用密钥对的形式连接阿里云服务器

CV learning notes - camera model (Euclidean transformation and affine transformation)

1. Finite Markov Decision Process

03 fastjason solves circular references

Opencv feature extraction sift

The underlying principle of vector
![[untitled] proteus simulation of traffic lights based on 89C51 Single Chip Microcomputer](/img/90/4de927e797ec9c2bb70e507392bed0.jpg)
[untitled] proteus simulation of traffic lights based on 89C51 Single Chip Microcomputer

Mobile phones are a kind of MCU, but the hardware it uses is not 51 chip
随机推荐
Leetcode - 460 LFU cache (Design - hash table + bidirectional linked hash table + balanced binary tree (TreeSet))*
LeetCode - 5 最长回文子串
Of course, the most widely used 8-bit single chip microcomputer is also the single chip microcomputer that beginners are most easy to learn
Leetcode 300 longest ascending subsequence
51 MCU tmod and timer configuration
01仿B站项目业务架构
Application of external interrupts
QT self drawing button with bubbles
2021-10-28
Leetcode - 1670 conception de la file d'attente avant, moyenne et arrière (conception - deux files d'attente à double extrémité)
Positive and negative sample division and architecture understanding in image classification and target detection
Leetcode - 933 number of recent requests
One click generate traffic password (exaggerated advertisement title)
Mobile phones are a kind of MCU, but the hardware it uses is not 51 chip
Stm32 NVIC interrupt priority management
My 4G smart charging pile gateway design and development related articles
Installation and removal of MySQL under Windows
QT detection card reader analog keyboard input
CV learning notes alexnet
LeetCode 面试题 17.20. 连续中值(大顶堆+小顶堆)