Deepest Leaves Sum
Medium
Topics
Given the root of a binary tree, return the sum of values of its deepest leaves.
Example 1
null marks a missing child.Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15
Example 2
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19
Constraints
- 1 <= number of nodes <= 10^4
- 1 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
We want the sum of the values at the greatest depth. A DFS tracking depth works: find the maximum depth, then sum the nodes at it — either in two passes, or in one by resetting the total whenever a deeper level appears.
A level-by-level BFS makes it almost free. Process the tree one complete level at a time and, at the start of each level, reset the running total. When the queue empties, the total holds whatever the last level contributed — no depth bookkeeping and no second pass.
The mechanism that makes "one complete level at a time" work is capturing len(queue) before the inner loop. That count is exactly the current level's width, so the loop consumes this level and enqueues the next without the two mixing.
Approach
- Queue with the root.
- While the queue is non-empty: reset the total, then process exactly
len(queue)nodes, adding values and enqueuing children. - Return the total.
Dry Run
tree 1
/ \
2 3
/ \ \
4 5 6
/
7
level 0 [1] total = 1
level 1 [2,3] total reset, = 5
level 2 [4,5,6] total reset, = 15
level 3 [7] total reset, = 7
queue empty
answer 7The reset at the top of each level is the whole trick: every level overwrites the previous total, so the last one to run is the one that survives.
Complexity
- Time — O(n): each node enqueued and dequeued once.
- Space — O(w): the queue holds at most one level, where
wis the widest level — up to n/2 for a complete tree. A DFS would be O(h) instead, which is better on a wide shallow tree and worse on a deep thin one.
Common Pitfalls
- Not capturing the level size before the inner loop. Reading
len(queue)inside it mixes levels and the reset lands in the wrong place. - Accumulating across levels instead of resetting, which sums the whole tree.
- Resetting after the level rather than before, which leaves the total at 0.
- Assuming the deepest level is a single node. It can hold several, and all of them count.
- Not guarding an empty tree, though the constraints here promise at least one node.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def deepestLeavesSum(self, root):
from collections import deque
q = deque([root]); total = 0
while q:
total = 0
for _ in range(len(q)):
n = q.popleft(); total += n.val
if n.left: q.append(n.left)
if n.right: q.append(n.right)
return totalimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int deepestLeavesSum(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int total = 0;
while (!q.isEmpty()) {
int sz = q.size();
total = 0;
for (int i = 0; i < sz; i++) {
TreeNode n = q.poll();
total += n.val;
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
}
return total;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int deepestLeavesSum(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int total = 0;
while (!q.empty()) {
int sz = q.size();
total = 0;
for (int i = 0; i < sz; i++) {
TreeNode* n = q.front();
q.pop();
total += n->val;
if (n->left) q.push(n->left);
if (n->right) q.push(n->right);
}
}
return total;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var deepestLeavesSum = function(root) {
let q = [root], total = 0;
while (q.length) {
const nq = [];
total = 0;
for (const n of q) {
total += n.val;
if (n.left) nq.push(n.left);
if (n.right) nq.push(n.right);
}
q = nq;
}
return total;
};