Share C++/C# (12ms/168ms) simple recursive solution


  • 3
    O

    C++ version

    bool hasPathSum(TreeNode* root, int sum) {
        if(root == NULL)
            return false;
        if(root->left == NULL && root->right == NULL && root->val == sum) 
            return true;
        return hasPathSum(root->left, sum-root->val) || 
        hasPathSum(root->right, sum-root->val);
    }
    

    C# version

    public bool HasPathSum(TreeNode root, int sum) {
        if(root == null)
            return false;
        if(root.left == null && root.right == null && root.val == sum) 
            return true;
        return HasPathSum(root.left, sum-root.val) || 
        HasPathSum(root.right, sum-root.val); 
    }

Log in to reply
 

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