Let the node tells itself it's left or right. No need other variables nor accessing descendant

  • 0
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            return sumOfLeftLeaves(root, false);

    Passing additional argument to tell if you (the node) is left or right.
    Right tree can still return left leaves back.

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

Log in to reply

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