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.

For example:
Given the below binary tree and sum = 22,

              5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!root) return false;
flag = false;
target = sum;
preOrder(root,);
return flag; }
void preOrder(TreeNode* node,int sum){
sum = node->val + sum; //递归前,加上当前节点
if(node->left)
{
preOrder(node->left,sum);
}
if(node->right)
{
preOrder(node->right,sum);
}
if(!node->left && !node->right && sum == target) //递归结束条件:到了叶子节点
{
flag = true;
}
}
private:
bool flag;
int target;
};

最新文章

  1. SASS 编译后去掉缓存文件和map文件
  2. input---checked小问题
  3. [SAP ABAP开发技术总结]选择屏幕——SELECT-OPTIONS
  4. 初识 Asp.Net内置对象之Request对象
  5. [转]Speeding Up Websites With YSlow
  6. Cocos2d-x3.0TestCpp文件夹笔记(二)
  7. 高效率使用google
  8. 自制单片机之十八……无线通讯模块NRF24L01+
  9. 10-2[RF] OOB validation
  10. Redis安装与基本配置(转)
  11. error C2448 函数样式初始值设定项类似函数定义
  12. Vultr VPS测试IP $5/月KVM-512MB/15G SSD/1T
  13. 3.1 cron表达式
  14. LVS-NAT模式的配置详解
  15. oracle 10g数据库下的 XDB组件的重新安装
  16. 认识 WebService
  17. C++读取与保持图片
  18. 设计模式—模板方法的C++实现
  19. 学习笔记(4)——实验室集群管理结点IP配置
  20. Spring IOC - 控制反转(依赖注入) - 入门案例 - 获取对象的方式 - 别名标签

热门文章

  1. 在Centos中yum安装和卸载软件的使用方法(转)
  2. phpMyAdmin“缺少 mcrypt 扩展。请检查 PHP 配置。”解决办法
  3. J2EE项目在weblogic下的改动
  4. python3api-ms-win-crt-runtime-l1-1-0.dll丢失解决方法
  5. A Complete Web Video Solution
  6. JDK 9 & JDK 10 新特性
  7. 二、Jetty的配置说明
  8. SQL 只取重复记录一条记录并且是最小值
  9. 在centOS5.9安装mysql
  10. ThinkPHP实例—实现登录验证