5 lines JAVA solution with recursion


  • 0
    Y
    public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        
        if (root==null) return false;
        if (root.left==null && root.right==null && root.val == sum) return true;
        
        if (hasPathSum(root.left,sum-root.val)) return true;
        if (hasPathSum(root.right, sum-root.val)) return true;
        return false;
        
        
        
        
    }
    

    }


  • 0

    My 4 line answer just for reference:

    public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {

        if(root==null){ return false;}
        sum=sum-root.val;
        if(sum==0&&root.left==null&&root.right==null) return true;
        return hasPathSum(root.left,sum)||hasPathSum(root.right,sum);
        
    }
    

    }


Log in to reply
 

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