meta data for this page
  •  

Sum of Left Leaves

Leetcode


Given the root of a binary tree, return the sum of all left leaves.

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Example 1:

assets.leetcode.com_uploads_2021_04_08_leftsum-tree.jpg

Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.

Solution 1

Solution 1

public int sumOfLeftLeaves(TreeNode root) {
  return sum(root, false);
}
 
public int sum(TreeNode root, boolean addRoot) {
  if (root == null) {
    return 0;
  }
  int val = 0;
  if (addRoot && root.left == null && root.right == null) {
    val += root.val;
  }
  return val + sum(root.left, true) + sum(root.right, false);
}