/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool dfs(TreeNode* tNode, int currentSum, int targetSum){
if(!tNode){
return false;
}else if(!tNode->left && !tNode->right){
if(tNode->val + currentSum == targetSum){
return true;
}
}else{
currentSum += tNode->val;
return dfs(tNode->left, currentSum, targetSum) || dfs(tNode->right, currentSum, targetSum);
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
return dfs(root, 0, targetSum);
}
};
LeetCode 112. 路径总和
最新推荐文章于 2024-11-09 21:51:15 发布