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. Sorted: [3,2,1]. 3rd largest is 1.
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 Sum in a Binary Tree INPUT Binary Tree Structure 5 Level 0 8 9 Level 1 2 1 3 7 Level 2 root = [5,8,9,2,1,3,7] k = 2 ALGORITHM STEPS 1 BFS Level Traversal Calculate sum at each level 2 Compute Level Sums L0=5, L1=17, L2=13 3 Build Min-Heap (size k) Keep k largest sums 4 Return Heap Top kth largest is min in heap Level Sums: Level 0: 5 Level 1: 17 Level 2: 13 Min-Heap (k=2): 13 17 min = 13 FINAL RESULT Sorted Level Sums (descending): 17 1st 13 2nd 5 3rd k = 2 OUTPUT 13 2nd largest level sum (Level 2: 2+1+3+7 = 13) OK - Answer: 13 Key Insight: BFS naturally processes nodes level by level, making it ideal for computing level sums. A min-heap of size k efficiently maintains the k largest values seen so far. The heap's minimum element is the kth largest. Time: O(n log k), Space: O(n) for queue + O(k) for heap. TutorialsPoint - Kth Largest Sum in a Binary Tree | BFS + Min-Heap Approach
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