One-line Java Solution, recursive


  • 0

    Just one line, very long, hard to read.

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            return root == null ? 0 : (((root.left != null && root.left.left == null && root.left.right == null) ? root.left.val : 0) + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right));
        }
    }
    

    its logic is same as the below solution.

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int res = 0;
            if (root.left != null && root.left.left == null && root.left.right == null) {
                res = root.left.val;
            }
            res += sumOfLeftLeaves(root.left);
            res += sumOfLeftLeaves(root.right);
            return res;
        }
    }
    

    Enjoy!


Log in to reply
 

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