首先使用最直观的解法,思路是递归从上向下,调用hasPathSum时targetSum减去当前结点值。当到达叶子结点时判断当前传入的targetSum是否和本结点相同。

/**
 * 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 == nullptr &&
          root->right == nullptr &&
          root->val == targetSum){
            return true;
        }
        bool l = hasPathSum(root->left,targetSum - root->val);
        if(l) return true;
        bool r = hasPathSum(root->right,targetSum - root->val);
        if(r) 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 == nullptr &&root->right == nullptr &&root->val == targetSum){
            return true;
        }
        
        return hasPathSum(root->left,targetSum - root->val) || hasPathSum(root->right,targetSum - root->val);
    }
};

程序执行效率:

Runtime: 8 ms, faster than 93.97% of C++ online submissions for Path Sum.
Memory Usage: 21.4 MB, less than 51.71% of C++ online submissions for Path Sum.