题解 | #牛的奶量统计#
牛的奶量统计
https://www.nowcoder.com/practice/213c039668804add9513bbee31370248
题目考察的知识点:二叉树的遍历
题目解答方法的文字分析:遍历这颗树,然后每次减结点的值,如果到页结点,t为0,则返回true。
本题解析所用的编程语言:c++
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param targetSum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int targetSum) {
// write code here
if (!root)
return false;
targetSum -= root->val;
if (!root->left && !root->right && targetSum == 0) return true;
return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}
};
