当前位置:网站首页>112. 路径总和
112. 路径总和
2022-04-23 09:04:00 【yitahutu79】
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。
示例 2:
输入:root = [1,2,3], targetSum = 5
输出:false
解释:树中存在两条根节点到叶子节点的路径:
(1 --> 2): 和为 3
(1 --> 3): 和为 4
不存在 sum = 5 的根节点到叶子节点的路径。
示例 3:
输入:root = [], targetSum = 0
输出:false
解释:由于树是空的,所以不存在根节点到叶子节点的路径。
提示:
树中节点的数目在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
bool hasPathSum(struct TreeNode* root, int targetSum){
if (root == NULL) return false;
if (root->left == NULL && root->right == NULL) return root->val == targetSum;
return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
}
版权声明
本文为[yitahutu79]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_40713201/article/details/124357456
边栏推荐
猜你喜欢
小程序报错:Cannot read property 'currentTarget' of undefined
valgrind和kcachegrind使用运行分析
GoLand debug go use - white record
Cadence process angle simulation, Monte Carlo simulation, PSRR
MATLAB入门资料
Strength comparison vulnerability of PHP based on hash algorithm
Common errors of VMware building es8
Experimental report on analysis of overflow vulnerability of assembly language and reverse engineering stack
Harbor enterprise image management system
Matlab draw five-star red flag
随机推荐
Valgrind et kcachegrind utilisent l'analyse d'exécution
2021李宏毅机器学习之Adaptive Learning Rate
[58] length of the last word [leetcode]
tsdf +mvs
2021 Li Hongyi's adaptive learning rate of machine learning
是否同一棵二叉搜索树 (25 分)
Enterprise wechat application authorization / silent login
Idea package jar file
Please arrange star trek in advance to break through the new playing method of chain tour, and the market heat continues to rise
L2-3 romantic silhouette (25 points)
On array replication
PCTP考试经验分享
单片机数码管秒表
Judgment on heap (25 points) two insertion methods
Trc20 fund collection solution based on thinkphp5 version
Consensus Token:web3.0生态流量的超级入口
考研线性代数常见概念、问题总结
Rembg split mask
Common errors of VMware building es8
Pctp test experience sharing