Sum of Left Leaves

Easy TreeDFS

Problem

Given the root of a binary tree, return the sum of the values of all leaves that are LEFT children.

Example 1 Input: [3,9,20,null,null,15,7] Output: 24

Constraints

Approach — Tree Traversal

This is a Tree Traversal problem. The idea: traverse the tree — DFS recursively, or BFS level by level — and combine the results from each subtree. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time.

Solution code

Python

class Solution:
    def sumOfLeftLeaves(self, root):
        def dfs(node, is_left):
            if not node:
                return 0
            if not node.left and not node.right:
                return node.val if is_left else 0
            return dfs(node.left, True) + dfs(node.right, False)
        return dfs(root, False)

Java

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        return dfs(root, false);
    }
    private int dfs(TreeNode n, boolean isLeft) {
        if (n == null) return 0;
        if (n.left == null && n.right == null) return isLeft ? n.val : 0;
        return dfs(n.left, true) + dfs(n.right, false);
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Sum of Left Leaves interactively → ← All solutions