Sum of Left Leaves

Add up the values of all the leaves in a binary tree that hang on the left side of their parent.

Given the root of a binary tree, return the sum of the values of all its left leaves. A leaf is a node with no children, and a left leaf is a leaf that is the left child of its parent. If the tree has no left leaves, return 0.

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 24
Explanation: 9 and 15 are left leaves, and 9 + 15 = 24.
Example 2
Input: root = [1]
Output: 0
Explanation: the only node is a leaf, but it has no parent, so it is not a left child.
Solution

The Idea

Example 1 writes the tree row by row. The top row holds 3. The next row holds 9 and 20. Then come the children of 9, both missing and written as null, and the children of 20, which are 15 and 7. Look at the picture below.

The tree of Example 1: root 3 with left child 9 and right child 20, and 20 with left child 15 and right child 7. 9 and 15 are marked as left leaves, 7 as a right leaf that is skipped, and 9 + 15 = 24.

The node at the top, 3, is the root. Each line runs from a parent down to a child and is labelled left or right by the side the child hangs on. Every node has at most two children, one on each side, which is what makes this a binary tree. The nodes 9, 15 and 7 have no children of their own, so they are leaves.

9 hangs on the left of 3, and 15 on the left of 20, so they are marked "left leaf: add 9" and "left leaf: add 15". 7 is a leaf too, but it hangs on the right of 20, so it is marked "right leaf: skip". The answer is 9 + 15 = 24.

Example 2 is a tree with the single node 1. It is a leaf, but no node is above it, so it is nobody's left child, and the answer is 0.

How can a program tell that 9 is a left leaf? Standing on 9 itself, it cannot. A node keeps its value and links down to its two children, but no link up to its parent, so 9 does not know which side it hangs on. Its parent does: from 3, the program follows the left link, finds 9 with no children, and adds 9.

So the test belongs one level up. At every node, ask whether its left child is a leaf. To ask that at every node, the program visits the whole tree with a method that handles one node and then calls itself on that node's children. A method that solves a problem by calling itself on smaller parts of it is called recursive.

Solution Approach

Three things need settling: what a call tests at its node, which children it goes on to, and where the calls stop.

The test at each node

What exactly does a call look at? It takes its node's left child and checks that the child exists and has neither a left nor a right child. If so, the child is a left leaf, and its value goes into the sum. At 3 the test passes for 9, and at 20 it passes for 15. At 9, 15 and 7 it fails, because they have no left child at all.

Which children to visit

When the left child is not a leaf, can the call ignore it? No, because left leaves may sit further down. In the tree [1, 2, 3, 4, 5], the root's left child 2 has children 4 and 5, and 4 is a left leaf. So when the test fails, the call goes on into the left child. A left leaf needs no call of its own, since nothing hangs below it.

The right child is always visited. A right child and everything below it, called its subtree, can hold left leaves too, just as the subtree of 20 holds 15 in Example 1.

Where the calls stop

When does the recursion end? A call on a missing child, which is null in Java, returns 0, since an empty spot holds no leaves. Each call adds what its child calls return to what it found itself, so the sums travel back up to the root. In Example 2, the node 1 has no left child, so the test fails, both child calls return 0, and the answer is 0.

Java Solution

The method sumOfLeftLeaves works in these steps:

  1. First, if root is null, return 0: an empty tree, or a missing child, holds no left leaves.
  2. Start a counter sum at 0, and keep the node's left child in a variable named left.
  3. If left is not null and both left.left and left.right are null, left is a left leaf, so add left.val to sum.
  4. Otherwise, call sumOfLeftLeaves(left) and add what it returns, to collect the left leaves below the left child.
  5. Finally, call sumOfLeftLeaves(root.right) for the right subtree, and return sum plus its result.

The class also holds a small TreeNode class and a build helper that makes a tree from the row-by-row form. The main method runs both examples, an empty tree, the tree [1, 2, 3, 4, 5] and the tree [1, 2, null, null, 3].

Java
public class SumOfLeftLeaves {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public static int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int sum = 0;
        TreeNode left = root.left;
        if (left != null && left.left == null && left.right == null) {
            sum += left.val;                  // the left child is a leaf
        } else {
            sum += sumOfLeftLeaves(left);     // look for left leaves further down
        }
        return sum + sumOfLeftLeaves(root.right);
    }

    // Builds a tree from the row-by-row form, with null for a missing child.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        java.util.ArrayDeque<TreeNode> queue = new java.util.ArrayDeque<>();
        queue.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode node = queue.poll();
            if (values[i] != null) {
                node.left = new TreeNode(values[i]);
                queue.add(node.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                node.right = new TreeNode(values[i]);
                queue.add(node.right);
            }
            i++;
        }
        return root;
    }

    static void run(String input, TreeNode root) {
        System.out.println(input + " -> " + sumOfLeftLeaves(root));
    }

    public static void main(String[] args) {
        run("[3, 9, 20, null, null, 15, 7]", build(3, 9, 20, null, null, 15, 7));
        run("[1]", build(1));
        run("[]", build());
        run("[1, 2, 3, 4, 5]", build(1, 2, 3, 4, 5));
        run("[1, 2, null, null, 3]", build(1, 2, null, null, 3));
    }
}

Running it prints:

Output
[3, 9, 20, null, null, 15, 7] -> 24
[1] -> 0
[] -> 0
[1, 2, 3, 4, 5] -> 4
[1, 2, null, null, 3] -> 0

Example 1 gives 24, from 9 and 15, and the single node [1] gives 0. The empty tree [] also gives 0, straight from the null check at the top of the method.

Look at the line [1, 2, 3, 4, 5] -> 4. The root's left child 2 is not a leaf, so the else branch calls the method on 2, and that call finds its own left child 4 is a leaf. The right leaves 5 and 3 add nothing.

The last line shows that being on the left side of the tree is not enough. In [1, 2, null, null, 3], the only leaf, 3, sits below the root's left child 2, but it is the right child of 2, so the result is 0.

Why not simply add every leaf the recursion reaches? A version that does that prints 31 for Example 1 (9 + 15 + 7) and 1 for Example 2. Once it stands on a leaf, it no longer knows which side it came from, so it counts the right leaf 7 and the lone root as well.

Complexity

The work is one call per node, except for left leaves, which their parent's test handles, and each call does a fixed amount of work.

  • Time: O(n), because the n nodes and at most n + 1 missing children each get at most one call, and every call does one test and two additions.
  • Space: O(h), where h is the number of nodes on the longest path from the root down to a leaf, because the calls still waiting for an answer always lie along one such path. That is about log n for a tree whose rows are all full and up to n for a tree that is a single chain.

Collecting every path from the root down to a leaf instead is Binary Tree Paths.