Simple C++ Solution


  • 0
    M
    bool hasPathSum(TreeNode* root, int sum) {
            if(!root)
                return false;
            return check(root, 0, sum);
        }
        
        bool check(TreeNode* root, int parentSum, int sum){
            int currentSum = root->val + parentSum;
            
            if(!root->left && !root->right) 
                return currentSum == sum;
            if(!root->left)
                return check(root->right, currentSum, sum);
            if(!root->right)
                return check(root->left, currentSum, sum);
            return check(root->left, currentSum, sum) || check(root->right, currentSum, sum);
        }
    

Log in to reply
 

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