题解 | #牛的奶量统计# 自顶向下DFS
牛的奶量统计
https://www.nowcoder.com/practice/213c039668804add9513bbee31370248
知识点
DFS
思路
自顶向下去维护从根节点到子节点的路径和,当子节点为叶子节点时更新答案。
注意当res已经为true或者路径和已经大于target时的及时剪枝。
时间复杂度
每个节点至多访问一次,时间复杂度为
AC code (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) {
bool res = false;
function<void(TreeNode*, int)> dfs = [&](TreeNode* root, int sum) {
if (!root or res) return;
sum += root->val;
if (!root->left and !root->right) {
if (sum == targetSum) {
res = true;
return;
}
}
if (sum < targetSum) {
if (root->left) dfs(root->left, sum);
if (root->right) dfs(root->right, sum);
}
};
dfs(root, 0);
return res;
}
};
