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
Kth Largest Level Sum: k=2 Example5Level 0: 589Level 1: 172137Level 2: 13Level Sums ProcessingLevel 0: 5Level 1: 8 + 9 = 17Level 2: 2 + 1 + 3 + 7 = 13Sorted: [17, 13, 5]Find 2nd LargestAnswer: 13k=2, so return 2nd element🎯 Key Insight: BFS naturally processes levels, making sum calculation straightforward
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
Asked in
Meta 15 Amazon 12 Google 8 Microsoft 6
28.4K Views
Medium Frequency
~25 min Avg. Time
892 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