题目描述

给定一个二叉树和一个值sum,判断是否有从根节点到叶子节点的节点值之和等于sum的路径,
例如:
给出如下的二叉树,sum=22,
             5
             / \
           4    8
           /      / \
         11  13  4
         /  \          \
        7    2        1
返回true,因为存在一条路径5->4->11->2的节点值之和为22



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 andsum = 22,
             5
             / \
           4    8
           /      / \
         11  13  4
         /  \          \
        7    2        1

return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.

示例1

输入

复制

{1,2},0

输出

复制

false
示例2

输入

复制

{1,2},3

输出

复制

true


/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     *
     * @param root TreeNode类
     * @param sum int整型
     * @return bool布尔型
     */
    bool hasPathSum(TreeNode* root, int sum) {
        // write code here
        if (root==NULL){
            return false;
        }
        if(root->left ==NULL && root->right==NULL && sum-root->val==0)
            return true;
        return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val);
    }
};

最新文章

  1. Python函数参数学习笔记
  2. EF架构~linq模拟left join的两种写法,性能差之千里!
  3. C#手工注入辅助工具
  4. ACM Steps 2.1.7
  5. 《微信小程序七日谈》- 第四天:页面路径最多五层?导航可以这么玩
  6. linux mount (挂载命令)详解
  7. WebAPi性能
  8. post 相比get 有很多优点,为什么现在的HTTP通信中大多数请求还是使用get?
  9. 如何在程序中调用Caffe做图像分类
  10. hdu 1728 逃离迷宫(dFS+优先队列)
  11. js面向对象+一般方法的选项卡
  12. 快速排序 partition函数的所有版本比较
  13. Https系列之二:https的SSL证书在服务器端的部署,基于tomcat,spring boot
  14. 深入浅出Hadoop之HDFS
  15. Gradle-----搭建简单的Gradle项目
  16. 【Teradata Utility】使用SQL Assistant导出导入数据
  17. Homework:工作日 还是周末
  18. oracle 锁表sql 解锁
  19. mysql5.7 yum安装
  20. GAN 教程记录

热门文章

  1. 《凤凰项目:一个IT运维的传奇故事》读书笔记
  2. STM32之旅3——时钟数
  3. 算法进阶 (LIS变形) 固定长度截取求最长不下降子序列【动态规划】【树状数组】
  4. MySQL数据库的完全备份与恢复
  5. CSS元素的显示与隐藏
  6. Termux基础教程(一):技能部署
  7. 【应用服务 App Service】当使用EntityFrameWorkCore访问Sql Server数据库时,在Azure App Service会出现Cannot create a DbSet for ** because this type is not included in the model for the context的错误
  8. Bitmap 创建、转换、圆角、设置透明度
  9. Spring之IOC/DI(反转控制/依赖注入)_入门Demo
  10. 微服务调用之feign负载均衡及服务降级