Deepest Leaves Sum - Problem
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
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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code