2 lines Java


  • 0
    W

    Readable version 4 lines

    public int sumOfLeftLeaves(TreeNode node) {
        return sumOfLeftLeaves(node, false);
    }
    
    private int sumOfLeftLeaves(TreeNode node, boolean isLeft) {
        if (Objects.isNull(node)) return 0;
        if (Objects.isNull(node.left) && Objects.isNull(node.right)) return isLeft ? node.val : 0;
        return sumOfLeftLeaves(node.left, true) + sumOfLeftLeaves(node.right, false);
    }
    

    2 lines version

    public int sumOfLeftLeaves(TreeNode node) {
        return node == null ? 0 : sumOfLeftLeaves(node, false);
    }
    
    private int sumOfLeftLeaves(TreeNode node, boolean isLeft) {
        return node.left == null && node.right == null ? isLeft ? node.val : 0 : ((node.left == null ? 0 : sumOfLeftLeaves(node.left, true)) + (node.right == null ? 0 : sumOfLeftLeaves(node.right, false)));
    }
    

Log in to reply
 

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