Java solution with explanation

  • 0

    The idea is to count only the left leafs. For that, I am using a boolean flag to keep a note of it. I think it makes it super simple to remember without any other tricks. Here is the code:

      public int sumOfLeftLeaves(TreeNode root) {
            if(root==null) {
                return 0;
            return helper(false,root);
        private int helper(boolean isLeft, TreeNode root) {
            if(root.left==null && root.right==null) {
                return isLeft?root.val:0;
            //have any left child?
            int sum=0;
            if(root.left!=null) {
                sum += helper(true,root.left);
            if(root.right!=null) {
                sum += helper(false,root.right);
            return sum;

Log in to reply

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