当前位置:网站首页>LeetCode 112:路径总和
LeetCode 112:路径总和
2022-07-29 00:53:00 【斯沃福德】
题目:
思路:dfs
思路类似零钱兑换 ,每次向下递归时,把要凑的数sum 减去当前节点root的val,这样即得到下一层需要凑的钱,直到叶子节点的sum等于节点的val即返回true !
题目说的是根节点到叶子节点! 所以要遍历到底,使用后序遍历;
单层节点: 判断当前是否是叶子节点,是则判断sum和val是否相等; 若不是叶子节点,继续递归;
base case: 如果root==null ,return false;
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
// 必须要到叶子节点 !
// 必须遍历到底! dfs
// 遍历到叶子节点后不等于sum,则返回false;
if(root==null){
return false;
}
// 接住结果,回溯
boolean left=hasPathSum(root.left,sum-root.val);
boolean right=hasPathSum(root.right,sum-root.val);
// 当前节点:
// 左右为null才是叶子节点!
if(root.left==null && root.right==null){
// 遍历到底,此时root值=sum 才返回true !
return root.val==sum;
}
return left || right;
}
}
边栏推荐
- Test / development programmers rely on technology to survive the midlife crisis? Improve your own value
- 活动速递| Apache Doris 性能优化实战系列直播课程初公开,诚邀您来参加!
- 【golang】使用select {}
- uniapp createSelectorQuery(). Select get returns null error
- Lombook User Guide
- [hcip] experiment of republishing and routing strategy
- Merkel Studio - harmonyos implementation list to do
- [web technology] 1395 esbuild bundler HMR
- SQL injection of DVWA
- 一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力
猜你喜欢

Analyze OP based on autoware_ global_ Planner global path planning module re planning

Platofarm community ecological gospel, users can get premium income with elephant swap
![[observation] ranked first in SaaS of pure public cloud in three years, and yonsuite's](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[observation] ranked first in SaaS of pure public cloud in three years, and yonsuite's "flywheel effect"

【HCIP】MPLS 基础

HCIA configuration instance (ENSP)

Tomorrow infinite plan, 2022 conceptual planning scheme for a company's yuanuniverse product launch

Cloud native application comprehensive exercise

规划数学期末模拟考试一

规划数学期末考试模拟二
![关于df[‘某一列名’][序号]](/img/e2/179fb4eda695726e87bb483f65e04e.png)
关于df[‘某一列名’][序号]
随机推荐
Super scientific and technological data leakage prevention system, control illegal Internet behaviors, and ensure enterprise information security
Canal real-time parsing MySQL binlog data practice
ELS new box falls
ELS square movement
After understanding the composition of the URL of the website, we use the URL module, querystring module and mime module to improve the static website
560 and K
规划数学期末考试模拟二
What is the ISO assessment? How to do the waiting insurance scheme
[search] - DFS pruning and optimization
【HCIP】两个MGRE网络通过OSPF实现互联(eNSP)
Network security litigation risk: four issues that chief information security officers are most concerned about
PCL point cloud intensity image
uniapp createSelectorQuery(). Select get returns null error
Embedded sharing collection 23
剑指offer专项突击版第13天
JS事件简介
【golang】使用select {}
【搜索】—— 迭代加深/双向DFS/IDA*
Openpyxl merge cells
全面升级,淘宝/天猫api接口大全