当前位置:网站首页>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;
}
}
边栏推荐
- 围绕新市民金融聚焦差异化产品设计、智能技术提效及素养教育
- Event express | Apache Doris Performance Optimization Practice Series live broadcast course is open at the beginning. You are cordially invited to participate!
- HCIA configuration instance (ENSP)
- 【HCIP】MPLS 基础
- [SQL's 18 dragon subduing palms] 01 - Kang long regrets: introductory 10 questions
- Nacos installation guide on win system
- Openpyxl border
- ELMO,BERT和GPT简介
- [hcip] MPLS Foundation
- Where will Jinan win in hosting the first computing power conference?
猜你喜欢

Sigma-DSP-OUTPUT

560 和为 K 的子数组

Timer of BOM series

560 and K

【Web技术】1395- Esbuild Bundler HMR

Where will Jinan win in hosting the first computing power conference?
![[search] - DFS pruning and optimization](/img/d4/7c2fec02f5a6bcfa2d5e204398af01.png)
[search] - DFS pruning and optimization

【搜索】—— DFS之剪枝与优化

Analysis of Multi Chain use cases on moonbeam -- review of Derek's speech in Polkadot decoded 2022

mysql的执行顺序
随机推荐
HCIA configuration instance (ENSP)
Super scientific and technological data leakage prevention system, control illegal Internet behaviors, and ensure enterprise information security
Window object of BOM series
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
Django reports an error using pymsql module django.db.utils.operationalerror
JVM learning minutes
Plato launched the LAAS protocol elephant swap, which allows users to earn premium income
Read the recent trends of okaleido tiger and tap the value and potential behind it
【HCIP】两个MGRE网络通过OSPF实现互联(eNSP)
T-sne dimensionality reduction
Six simple techniques to improve the value of penetration testing and save tens of thousands of yuan
The information security and Standardization Commission issued the draft for comments on the management guide for app personal information processing activities
SQL injection of DVWA
BOM系列之window对象
【搜索】—— DFS之剪枝与优化
ELS stop at all
JS 定时器setInterval clearInterval 延时器setTimeOut 异步 动画
Understand all the basic grammar of ES6 in one article
Openpyxl merge cells
ELMO,BERT和GPT简介