正常版
/**
* 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 hasPathSum(TreeNode* root, int targetSum) {
if(!root) return false;
return traversal(root, targetSum - root->val);
}
private:
bool traversal(TreeNode* node, int count) const {
if(!node->left && !node->right) {
if(!count) return true;
if(count) return false;
}
if(node->left) {
if(traversal(node->left, count - node->left->val)) return true;
}
if(node->right) {
if(traversal(node->right, count - node->right->val)) return true;
}
return false;
}
};
精简版
/**
* 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 hasPathSum(TreeNode* root, int targetSum) {
if(!root) return false;
if(!root->left && !root->right) return root->val == targetSum;
return (hasPathSum(root->left, targetSum - root->val)) || (hasPathSum(root->right, targetSum - root->val));
}
};