leetcode 38:path-sum
2024-10-09 16:25:52
题目描述
给定一个二叉树和一个值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.
例如:
给出如下的二叉树,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.
示例2
输出
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);
}
};
最新文章
- Python函数参数学习笔记
- EF架构~linq模拟left join的两种写法,性能差之千里!
- C#手工注入辅助工具
- ACM Steps 2.1.7
- 《微信小程序七日谈》- 第四天:页面路径最多五层?导航可以这么玩
- linux mount (挂载命令)详解
- WebAPi性能
- post 相比get 有很多优点,为什么现在的HTTP通信中大多数请求还是使用get?
- 如何在程序中调用Caffe做图像分类
- hdu 1728 逃离迷宫(dFS+优先队列)
- js面向对象+一般方法的选项卡
- 快速排序 partition函数的所有版本比较
- Https系列之二:https的SSL证书在服务器端的部署,基于tomcat,spring boot
- 深入浅出Hadoop之HDFS
- Gradle-----搭建简单的Gradle项目
- 【Teradata Utility】使用SQL Assistant导出导入数据
- Homework:工作日 还是周末
- oracle 锁表sql 解锁
- mysql5.7 yum安装
- GAN 教程记录
热门文章
- 《凤凰项目:一个IT运维的传奇故事》读书笔记
- STM32之旅3——时钟数
- 算法进阶 (LIS变形) 固定长度截取求最长不下降子序列【动态规划】【树状数组】
- MySQL数据库的完全备份与恢复
- CSS元素的显示与隐藏
- Termux基础教程(一):技能部署
- 【应用服务 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的错误
- Bitmap 创建、转换、圆角、设置透明度
- Spring之IOC/DI(反转控制/依赖注入)_入门Demo
- 微服务调用之feign负载均衡及服务降级