LeetCode #404 Easy

Sum of Left Leaves

Sum of Left Leaves is LeetCode 404 (Easy). 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.
  • A left leaf is a leaf that is the left child of its parent.

Values can be negative, so the answer can be negative too. A tree with no left leaf returns 0.

Constraints
  • The number of nodes in the tree is in the range [1, 1000].
  • -1000 <= Node.val <= 1000
treedfs
Open on LeetCode ↗
02

Intuition

A node can see whether it is a leaf: it checks its own children. It cannot see whether it is a left child, because only its parent knows which link led to it. So let the parent pass that fact down as a flag: True into the left child, False into the right child.

  • Leaf with the flag set: a left leaf, so return its value.
  • Leaf without the flag: a right leaf or the root, so return 0.
  • Any other node: return the sum of what its two children return.

Every left leaf lies somewhere below the root, so visiting every node once and adding up the returns finds them all.

How to spot this pattern

When a node's answer depends on how you reached it, pass that fact down as an argument. Path Sum passes the remaining target and Binary Tree Paths passes the path so far in the same way.

03

Approach

Try it first

Before reading on, decide what a node can tell about itself and what only its parent knows. Then decide how that missing fact can reach the node. Aim for O(n) time.

1

Pass a left flag down

Define dfs(node, is_left). The caller sets the flag: True when it steps into a left child and False for a right child. The first call is dfs(root, False), since the root is nobody's child.

2

Return 0 for an empty spot

dfs(None, ...) returns 0, which adds nothing to the sum. A node with only one child can then call both sides without first checking which one exists, so the recursive line is the same for every node.

3

Decide at a leaf

If the node has no left and no right child, return node.val when is_left is true and 0 otherwise. This is the only place a value enters the sum.

4

Add up both sides

Any other node returns dfs(node.left, True) + dfs(node.right, False). The right side is searched too, because a right child can have left leaves of its own.

04

Code in Python, C++ and Java

▶1import sys
▶2 
▶3sys.setrecursionlimit(3000)
▶4 
▶5 
▶6class Solution:
▶7 def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
▶8 def dfs(node, is_left):
▶9 if not node:
▶10 return 0
▶11 if not node.left and not node.right:
▶12 return node.val if is_left else 0
▶13 return dfs(node.left, True) + dfs(node.right, False)
▶14 
▶15 return dfs(root, False)
tree3920157sum of left leaves03 has children → not a leaf, look below
node3
is_leftFalse
childrenleft and right
Node 3 has a left and a right child, so it is not a leaf and adds nothing itself. It calls its left child with True and its right child with False, because a left leaf can sit on either side below it.
tree39left leaf20157sum of left leaves99 is a leaf reached going left → add 9
node9
is_leftTrue
returns9
Node 9 has no children, and its parent passed is_left = True because it was reached through a left link. Both conditions hold, so it returns 9 into the sum.
tree39left leaf20157sum of left leaves920 has children → not a leaf, look below
node20
is_leftFalse
childrenleft and right
Node 20 has a left and a right child, so it is not a leaf and adds nothing itself. It calls its left child with True and its right child with False, because a left leaf can sit on either side below it.
tree39left leaf2015left leaf7sum of left leaves9+15=2415 is a leaf reached going left → add 15
node15
is_leftTrue
returns15
Node 15 has no children, and its parent passed is_left = True because it was reached through a left link. Both conditions hold, so it returns 15 into the sum.
tree39left leaf2015left leaf7right leafsum of left leaves9+15=247 is a leaf but a right child → adds 0
node7
is_leftFalse
returns0
Node 7 has no children, so it is a leaf, but it is a right child. Only leaves reached through a left link count, so it returns 0.
tree39left leaf2015left leaf7right leafsum of left leaves9+15=24answer: 24
return24
Every node has been visited once. The left leaves are 9 and 15, so the answer is 24.
05

Common pitfalls

Adding every left child

✗ Wrong
if node.left:
    total += node.left.val
✓ Right
if not node.left and not node.right:
    return node.val if is_left else 0

A left child with children of its own is not a leaf. On [1,2,null,null,3] this adds 2, but 2 has a right child, and 3 is a right leaf, so the answer is 0.

Starting the root as a left child

✗ Wrong
return dfs(root, True)
✓ Right
return dfs(root, False)

The root has no parent, so it is never a left leaf. On the single-node tree [1] this returns 1 instead of 0.

Reading a grandchild before checking the child exists

✗ Wrong
if not root.left.left and not root.left.right:
    total += root.left.val
✓ Right
if root.left and not root.left.left and not root.left.right:
    total += root.left.val

In the version where a parent tests its left child, [1,null,2] has no left child, so root.left.left raises AttributeError (a null-pointer crash in C++ or Java). Check root.left first.

06

Edge cases

A 1,000-node chain

The recursion goes 1,000 calls deep, just past Python's default limit of 1,000, so the code raises it with sys.setrecursionlimit. C++ and Java handle that depth with no change.

07

Complexity

Time
O(n)
Space
O(h)
n is the number of nodes and h the height of the tree. Each node is visited once and does constant work. The call stack holds one call per level: about log n for a balanced tree, up to n for a chain.
08

Sum of Left Leaves FAQ

Can it be done without recursion?

Keep a stack of (node, is_left) pairs, starting with (root, False). Pop a pair; if the node is a leaf and the flag is true, add its value; otherwise push its children, the left one with True and the right one with False. It is still O(n), with no recursion limit to raise.

How would you sum the right leaves instead?

Swap the flags: pass True to the right child and False to the left one, and keep the root at False. To sum every leaf, drop the flag and return node.val at each leaf.