Sharing my 3 lines C++ solution


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

  • 1
    R

    Clear code for 15ms

    bool hasPathSum(TreeNode *root, int sum) {
    if (root == NULL)
    {
    return false;
    }

        if ((root->left == NULL) && (root->right == NULL))
        {
            return sum == root->val;
        } 
        
        int nv = sum - root->val;
        
        return hasPathSum(root->left, nv) || hasPathSum(root->right, nv);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.