Java solution using a boolean variable - O(n)


  • 0
    F

    Using a isLeft variable to indicate this is a left node or not:

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            return helper(root, false);
        }
        
        private int helper(TreeNode root, boolean isLeft) {
            if (root == null) return 0;
            if (root.left == null && root.right == null && isLeft) return root.val;
            return helper(root.left, true) + helper(root.right, false);
        }
    }
    

Log in to reply
 

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