Kth Largest Sum in a Binary Tree - Problem
You are given the root of a binary tree and a positive integer k.
The level sum in the tree is the sum of the values of the nodes that are on the same level.
Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer than k levels in the tree, return -1.
Note that two nodes are on the same level if they have the same distance from the root.
Input & Output
Example 1 — Basic Tree
$
Input:
root = [5,8,9,2,1,3,7], k = 2
›
Output:
13
💡 Note:
Level sums: Level 0 = 5, Level 1 = 8+9 = 17, Level 2 = 2+1+3+7 = 13. Sorted: [17,13,5]. 2nd largest is 13.
Example 2 — Not Enough Levels
$
Input:
root = [1,2,null,3], k = 3
›
Output:
-1
💡 Note:
Level sums: Level 0 = 1, Level 1 = 2, Level 2 = 3. Only 3 levels exist, but k=3 asks for 3rd largest. Not enough levels.
Example 3 — Single Node
$
Input:
root = [1], k = 1
›
Output:
1
💡 Note:
Only one level with sum = 1. 1st largest level sum is 1.
Constraints
- The number of nodes in the tree is in the range [1, 105]
- 1 ≤ Node.val ≤ 106
- 1 ≤ k ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with multiple levels
2
Level Sums
Calculate sum for each level using BFS
3
Find Kth Largest
Return kth largest sum or -1 if not enough levels
Key Takeaway
🎯 Key Insight: BFS traversal naturally groups nodes by level, making it perfect for calculating level sums efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code