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
Floor 0 (Root): Value 3Floor 1: Value 5Floor 1: Value 1Floor 2: 6Floor 2: 2Floor 2: 8Floor 3: 7Floor 3: 4๐Ÿ† Sum = 7 + 4 = 11Elevator
Understanding the Visualization
1
Start at Ground Floor
Begin at the root (ground floor) and start exploring deeper floors
2
Track Highest Floor
As we visit each floor, keep track of the highest floor number reached
3
Collect Treasures
When we find a new highest floor, reset our treasure count. If we find more rooms on the same highest floor, add to our treasure count
4
Final Count
After visiting all rooms, return the total treasure from the highest floor
Key Takeaway
๐ŸŽฏ Key Insight: By tracking both the maximum depth and sum in a single traversal, we eliminate the need for multiple passes through the tree, achieving optimal O(n) time complexity.
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