递归解法
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
//已经抵达叶子节点,判断targetSum是否等于叶子节点的值即可
if (!root->left && !root->right) return root->val == targetSum;
//递归遍历左右子节点,目标和减去当前节点的值
return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
}
};