Super easy 3 lines Java solution


  • 5
    P

    I believe this is the easiest approach. Let me know if you can improve it.

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

    }


  • 0
    S

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

    funny man,aha


  • 0
    S

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

    same method with u, nice


Log in to reply
 

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