当前位置:网站首页>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
边栏推荐
- Resource packaging dependency tree
- Latex mathematical formula
- Talent Plan 学习营初体验:交流+坚持 开源协作课程学习的不二路径
- Applet in wechat and app get current ()
- 共享办公室,提升入驻体验
- To remember the composition ~ the pre order traversal of binary tree
- Data visualization: use Excel to make radar chart
- ATSS(CVPR2020)
- MySQL小練習(僅適合初學者,非初學者勿進)
- 1099 establish binary search tree (30 points)
猜你喜欢

Automatic differentiation and higher order derivative in deep learning framework

To remember the composition ~ the pre order traversal of binary tree

npm ERR! network

Correct method of calculating inference time of neural network

Idea package jar file

Project upload part

共享办公室,提升入驻体验

Open services in the bottom bar of idea

Download and install bashdb

Flink SQL realizes the integration of stream and batch
随机推荐
是否完全二叉搜索树 (30 分)
Latex mathematical formula
Taxable income
2021 Li Hongyi's adaptive learning rate of machine learning
Enterprise wechat application authorization / silent login
MATLAB入门资料
Illegal character in scheme name at index 0:
Experimental report on analysis of overflow vulnerability of assembly language and reverse engineering stack
Brush classic topics
Concave hull acquisition method based on convex hull of point cloud
Latex paper typesetting operation
Number theory to find the sum of factors of a ^ B (A and B are 1e12 levels)
valgrind和kcachegrind使用運行分析
L2-023 graph coloring problem (25 points) (graph traversal)
Restore binary tree (25 points)
Study notes of deep learning (8)
在sqli-liabs学习SQL注入之旅(第十一关~第二十关)
To remember the composition ~ the pre order traversal of binary tree
Whether the same binary search tree (25 points)
Initial experience of talent plan learning camp: communication + adhering to the only way to learn open source collaborative courses