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
Example 1
Output: 24
Explanation: 9 and 15 are left leaves, and 9 + 15 = 24.
Example 2
Output: 0
Explanation: the only node is a leaf, but it has no parent, so it is not a left child.
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 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 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
Java Solution
The method sumOfLeftLeaves
- First, if
isroot , return 0: an empty tree, or a missing child, holds no left leaves.null - Start a counter
at 0, and keep the node's left child in a variable namedsum .left - If
is notleft and bothnull andleft.left areleft.right ,null is a left leaf, so addleft toleft.val .sum - Otherwise, call
and add what it returns, to collect the left leaves below the left child.sumOfLeftLeaves(left) - Finally, call
for the right subtree, and returnsumOfLeftLeaves(root.right) plus its result.sum
The class also holds a small TreeNodebuildmain[1, 2, 3, 4, 5][1, 2, null, null, 3]
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:
[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][]null
Look at the line [1, 2, 3, 4, 5] -> 4else
The last line shows that being on the left side of the tree is not enough. In [1, 2, null, null, 3]
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