Sum of Deepest Leaves in Binary Tree

Imagine you have a binary tree where leaves at different levels contain valuable treasures. Your mission is to find all leaves that are at the deepest level (farthest from the root) and calculate the total sum of their values.

📋 Task: Given the root of a binary tree, return the sum of values of its deepest leaves.

🎯 Goal: Identify the maximum depth of the tree, then sum all leaf nodes that exist at this maximum depth.

💡 Example: In a tree with depths 0, 1, 2, if the deepest leaves at level 2 have values [4, 5, 6], return 15.

Input & Output

example_1.py — Python
$ Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
💡 Note: The tree has maximum depth 3. Nodes at depth 3 are [7, 8]. Sum = 7 + 8 = 15.
example_2.py — Python
$ Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19
💡 Note: The deepest leaves are at depth 4. The deepest leaves are [9, 1, 4, 5]. Sum = 9 + 1 + 4 + 5 = 19.
example_3.py — Python
$ Input: root = [1]
Output: 1
💡 Note: Edge case: single node tree. The root is the only and deepest leaf with value 1.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • 1 ≤ Node.val ≤ 100
  • All node values are positive integers

Visualization

Tap to expand
Deepest Leaves Sum - DFS Approach INPUT Binary Tree Structure 1 2 3 4 5 6 7 8 D=0 D=1 D=2 D=3 Green = Deepest Leaves root = [1,2,3,4,5, null,6,7,null,null,null,null,8] Max Depth = 3 ALGORITHM STEPS 1 Initialize DFS maxDepth=0, sum=0 Start from root 2 Traverse Tree (DFS) Track current depth Visit all nodes recursively 3 Update Max Depth If depth > maxDepth: reset sum, update max 4 Sum Deepest Leaves If depth == maxDepth: add node.val to sum DFS Traversal Order: 1 --> 2 --> 4 --> 7(D3) --> 5 --> 3 --> 6 --> 8(D3) Found leaves at depth 3: 7, 8 Sum = 7 + 8 = 15 FINAL RESULT Deepest Leaves Identified 1 2 3 4 6 7 8 7 + 8 = 15 Sum of Deepest Leaves Output: 15 Key Insight: DFS traversal tracks depth as we go deeper. When we find a new maximum depth, we reset the sum and start fresh. If we reach a leaf at the current max depth, we add its value to the sum. Time: O(n) - visit each node once | Space: O(h) - recursion stack where h = tree height TutorialsPoint - Deepest Leaves Sum | DFS Approach
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 24 Apple 18
58.9K Views
Medium Frequency
~18 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen