LeetCode112 Path Sum
2024-10-08 00:42:36
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. (Easy)
For example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
分析:
还是用递归的思路,可以把sum - root -> val用在递归函数中,这样写最简洁。
代码:
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == nullptr) {
return false;
}
if(root -> right == nullptr && root -> left == nullptr) {
return sum == root->val;
}
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val) ;
}
};
最新文章
- iOS 开发:TCP三次握手连接
- Google 开源技术protobuf
- python virtualenv环境运行django
- 多列布局——column-width
- iconv 的参数问题
- HDU 5818 Joint Stacks(左偏树)
- Java基础知识二次学习--第五章 数组
- 壮美大山包-2017中国大山包国际超百公里ITRA积分赛赛记
- ARVE: Augmented Reality Applications in Vehicle to Edge Networks
- Android开发,关于如何在应用间共享SharedPreference
- 轴对称 Navier-Stokes 方程组的一个点态正则性准则
- SpringAOP面向切面编程
- SQL Server生成数据库的数据字典存储过程
- 爬虫——request
- [转载]前端——实用UI组件库
- iframe刷新父页面
- 532 -数组中的K-diff对
- 基于STM32F103ZET6 HC_SR04超声波测距模块
- Jersey入门三:创建一个JavaEE的Web项目
- cygwin安装方法