当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
Learn SQL injection in sqli liabs (Level 11 ~ level 20)
Judgment on heap (25 points) two insertion methods
Notes d'apprentissage oneflow: de functor à opexprinterpreter
企业微信应用授权/静默登录
Consensus Token:web3.0生态流量的超级入口
To remember the composition ~ the pre order traversal of binary tree
Research purpose, construction goal, construction significance, technological innovation, technological effect
Leetcode-199 - right view of binary tree
Mini - exercice MySQL (seulement pour les débutants, pas pour les non - débutants)
Resource packaging dependency tree
LeetCode_ DFS_ Medium_ 1254. Count the number of closed islands
Write down the post order traversal of the ~ binary tree
Whether the same binary search tree (25 points)
Output first order traversal according to second order and middle order traversal (25 points)
Rembg split mask
The K neighbors of each sample are obtained by packet switching
Applet in wechat and app get current ()
Withholding agent
论文阅读《Multi-View Depth Estimation by Fusing Single-View Depth Probability with Multi-View Geometry》
L2-022 rearrange linked list (25 points) (map + structure simulation)



![[C language] document operation](/img/89/b19dda13d27e37fedf6736c102245b.png)





