当前位置:网站首页>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;
}
}
边栏推荐
- Cloud native application comprehensive exercise
- els 方块移动
- Nacos installation guide on win system
- uniapp createSelectorQuery(). Select get returns null error
- Lombook User Guide
- Moonbeam上的多链用例解析——Derek在Polkadot Decoded 2022的演讲文字回顾
- 10 major network security incidents in the past 10 years
- [hcip] two mGRE networks are interconnected through OSPF (ENSP)
- [hcip] experiment of republishing and routing strategy
- How many of the top ten test tools in 2022 do you master
猜你喜欢
The information security and Standardization Commission issued the draft for comments on the management guide for app personal information processing activities
【Web技术】1395- Esbuild Bundler HMR
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
[search] - DFS pruning and optimization
规划数学期末模拟考试一
MySQL execution order
Super technology network security risk assessment service, comprehensively understand the security risks faced by the network system
Matplotlib Chinese question
什么是原码、反码和补码
如何选择专业、安全、高性能的远程控制软件
随机推荐
2022年最火的十大测试工具,你掌握了几个
Plato launched the LAAS protocol elephant swap, which allows users to earn premium income
The information security and Standardization Commission issued the draft for comments on the management guide for app personal information processing activities
The solution to keep the height of the container unchanged during the scaling process of the uniapp movable view table
SQL injection of DVWA
【GoLang】同步锁 Mutex
Code generator
数据库的decimal类型的数据,发现可以通过resultSet.getDouble去拿到这个数据,但是通过getObject却拿不到这个属性。
Analyze OP based on autoware_ global_ Planner global path planning module re planning
10 major network security incidents in the past 10 years
Lombook User Guide
560 and K
代码生成器
Canal real-time parsing MySQL binlog data practice
C language 300 lines of code to achieve mine sweeping (deployable + markable + changeable difficulty level)
全新升级:获得淘宝商品详情“高级版” API
Cloud native application comprehensive exercise
Reinforcement learning (I): Q-learning, with source code interpretation
560 和为 K 的子数组
Formal parameters, arguments, main function parameters, arrays or pointers as function parameters of the knowledge in every corner of C language