Easy Java solution with comment


  • 1
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     /*
     Basic idea: the sum of a node = f(leftSubTree) + f(rightSubtree)
     However we need to distinguish between left leaf or right leaf
     */
     
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            return helper(root, false);
        }
        
        private int helper(TreeNode root, boolean isLeft){
            if(root == null) return 0;
            /*This node is a leaf, if it's a left leaf, we return the value
              if it's a right leaf we return 0 since right leaf doesn't count*/
            if(root.left == null && root.right == null){
                if(isLeft){
                    return root.val;
                }
                return 0;
            }
            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.