Skip to main content

Leaf Node Depth Sum

easy
TreeDepth First SearchBinary TreeDfs Recursive
Asked atAmazonGoogleMicrosoft

Problem Description

Given the root of a binary tree, return the sum of the depths of all **leaf nodes**.

A leaf node is a node with no children. The depth of a node is the number of edges on the path from the root to that node (the root has depth 0).

**Example 1:**
```
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 5
Explanation:
- Node 9 is a leaf at depth 1
- Node 15 is a leaf at depth 2
- Node 7 is a leaf at depth 2
Sum = 1 + 2 + 2 = 5
```

**Example 2:**
```
Input: root = [1, 2, 3, 4, 5]
Output: 7
Explanation:
- Node 4 is a leaf at depth 2
- Node 5 is a leaf at depth 2
- Node 3 is a leaf at depth 1
Sum = 2 + 2 + 1 = 5... wait:
Actually: leaves are 4 (depth 2), 5 (depth 2), 3 (depth 1) → sum = 5
```

**Example 2 (corrected):**
```
Input: root = [1, 2, 3, 4, 5]
Output: 5
Explanation: Leaves are node 4 (depth 2), node 5 (depth 2), and node 3 (depth 1). Sum = 2 + 2 + 1 = 5.
```

Constraints

  • The number of nodes in the tree is in the range [1, 1000].
  • Node values are integers in the range [-100, 100].
  • Node values do not affect the answer — only structure matters.

Follow-up

Can you solve this iteratively using an explicit stack, avoiding recursion entirely?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.