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) ;
}
};

最新文章

  1. iOS 开发:TCP三次握手连接
  2. Google 开源技术protobuf
  3. python virtualenv环境运行django
  4. 多列布局——column-width
  5. iconv 的参数问题
  6. HDU 5818 Joint Stacks(左偏树)
  7. Java基础知识二次学习--第五章 数组
  8. 壮美大山包-2017中国大山包国际超百公里ITRA积分赛赛记
  9. ARVE: Augmented Reality Applications in Vehicle to Edge Networks
  10. Android开发,关于如何在应用间共享SharedPreference
  11. 轴对称 Navier-Stokes 方程组的一个点态正则性准则
  12. SpringAOP面向切面编程
  13. SQL Server生成数据库的数据字典存储过程
  14. 爬虫——request
  15. [转载]前端——实用UI组件库
  16. iframe刷新父页面
  17. 532 -数组中的K-diff对
  18. 基于STM32F103ZET6 HC_SR04超声波测距模块
  19. Jersey入门三:创建一个JavaEE的Web项目
  20. cygwin安装方法

热门文章

  1. Docker(五)安装Fastdfs
  2. H5C3--background中cover,背景样式,提升响应区域+精灵图的使用
  3. [转载]C语言EOF是什么?
  4. Java review-basic6
  5. IO流4 --- IO流体系 --- 技术搬运工(尚硅谷)
  6. Django ORM中的查询,删除,更新操作
  7. Python 数据文件操作——写出数据
  8. 【洛谷】P1876 开灯
  9. DLedger —基于 raft 协议的 commitlog 存储库
  10. LintCode_46 主元素