1ms Java Solution


  • -2
    L
    public class Solution {
    private boolean hasSum;
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return hasSum;
        if(root.left == null && root.right == null){
            return (root.val == sum);
        }
        if(root.left != null){
            dfs(root.left, root.val, sum);
            if(hasSum) return hasSum;
        }
        if(root.right != null){
            dfs(root.right, root.val, sum);
        }
        return hasSum;
    }
    
    private void dfs(TreeNode current, int curSum, int sum){
        curSum += current.val;
        if(current.left == null && current.right == null){
            hasSum = (curSum == sum);
            if(hasSum) return;
        }
        if(current.left!=null){
            dfs(current.left, curSum, sum);
            if(hasSum) return;
        }
        if(current.right!=null){
            dfs(current.right, curSum, sum);
            if(hasSum) return;
        }
    }
    

    }


  • 1
    Y

    1ms recursion solution:

    if(root==null) return false;
    if(root.val==sum && root.right==null && root.left==null) return true;

    return hasPathSum(root.left, (sum-root.val)) || hasPathSum(root.right, (sum-root.val));


  • 0
    Y

    1ms recursion solution:

    if(root==null) return false;
    if(root.val==sum && root.right==null && root.left==null) 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.