题目:
代码(首刷看解析 2024年1月30日 递归回溯 逻辑清晰版):
class Solution {
public:
bool traversal(TreeNode* cur,int sum) {
if (!cur->left && !cur->right && sum == 0) return true;
if (!cur->left && !cur->right) return false;
if (cur->left) {
sum -= cur->left->val;
if (traversal(cur->left,sum)) return true;
sum += cur->left->val;
}
if (cur->right) {
sum -= cur->right->val;
if (traversal(cur->right,sum)) return true;
sum += cur->right->val;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) return false;
return traversal(root,targetSum - root->val);
}
};
代码(代码简洁版)
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right && targetSum == root->val) return true;
return hasPathSum(root->left, targetSum - root->val) ||
hasPathSum(root->right, targetSum - root->val);
}
};