模拟面试遇到的题,第一次在十分钟内无错手撸出来,纪念一下

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
  public:
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    bool hasPathSum(TreeNode* root, int sum) {
      if (!root) {
        return false;
      }
      
      return recursion(root, sum, 0);
    }
  private:
    bool recursion(TreeNode *root, const int &sum, int count) {
      if (!root) {
        return false;
      }
      
      count += root->val;
      
      if (count == sum && !root->left && !root->right) {
        return true;
      }
      
      bool flag = false;
      flag |= recursion(root->left, sum, count);
      flag |= recursion(root->right, sum, count);
      
      return flag;
    }
};

大佬的解法

class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if(root == nullptr) return false;
        if(root->left == nullptr && root->right == nullptr) {
            return sum == root->val;
        }
        return (hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val));
    }
};