当前位置:网站首页>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
边栏推荐
- I don't understand time, timestamp and time zone. Look at this article
- Non duplicate data values of two MySQL query tables
- 是否完全二叉搜索树 (30 分)
- Whether the same binary search tree (25 points)
- 深度学习框架中的自动微分及高阶导数
- 【原创】使用System.Text.Json对Json字符串进行格式化
- Notes on xctf questions
- MySQL小練習(僅適合初學者,非初學者勿進)
- Valgrind et kcachegrind utilisent l'analyse d'exécution
- Introduction to GUI programming swing
猜你喜欢
随机推荐
LeetCode_ DFS_ Medium_ 1254. Count the number of closed islands
Production practice elk
L2-024 部落 (25 分)(并查集)
Leetcode-199 - right view of binary tree
valgrind和kcachegrind使用運行分析
2D 01 Backpack
Common errors of VMware building es8
ATSS(CVPR2020)
计算神经网络推理时间的正确方法
Non duplicate data values of two MySQL query tables
Go language self-study series | golang structure pointer
Valgrind and kcache grind use run analysis
Brief steps to build a website / application using flash and H5
DJ music management software pioneer DJ rekordbox
PLC point table (register address and point table definition) cracking detection scheme -- convenient for industrial Internet data acquisition
Talent Plan 学习营初体验:交流+坚持 开源协作课程学习的不二路径
npm报错 :operation not permitted, mkdir ‘C: \Program Files \node js \node_ cache _ cacache’
Notes d'apprentissage oneflow: de functor à opexprinterpreter
Write down the post order traversal of the ~ binary tree
L2-023 图着色问题 (25 分)(图的遍历)