#1302
Deepest Leaves Sum
MediumTreeDepth-First SearchBreadth-First SearchBinary TreeBreadth-First Search (BFS)Depth-First Search (DFS)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach uses a single traversal of the tree to simultaneously calculate the maximum depth and the sum of the deepest leaves. This is efficient and avoids redundant work.
⚙️
Algorithm
3 steps- 1Step 1: Use a queue for level order traversal (BFS) to explore each level of the tree.
- 2Step 2: For each level, sum the values of the nodes.
- 3Step 3: Continue until all levels are processed, returning the sum of the last level.
solution.py17 lines
1from collections import deque
2
3def deepestLeavesSum(root):
4 if not root:
5 return 0
6 queue = deque([root])
7 while queue:
8 level_sum = 0
9 level_size = len(queue)
10 for _ in range(level_size):
11 node = queue.popleft()
12 level_sum += node.val
13 if node.left:
14 queue.append(node.left)
15 if node.right:
16 queue.append(node.right)
17 return level_sumℹ
Complexity note: This complexity is due to the single traversal of the tree (O(n)) and the space used by the queue, which can hold up to O(n) nodes in the worst case.
- 1Using BFS allows us to efficiently calculate the sum of the deepest leaves in one pass.
- 2The maximum depth can be determined while summing the values, avoiding redundant traversals.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.