#2583

Kth Largest Sum in a Binary Tree

Medium
TreeBreadth-First SearchSortingBinary TreeHeapTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log k)
Space
O(n)
O(k)
💡

Intuition

Time O(n log k)Space O(k)

This approach uses a priority queue (min-heap) to efficiently keep track of the top k largest level sums while traversing the tree. This avoids the need for sorting the entire list of sums, making it faster.

⚙️

Algorithm

4 steps
  1. 1Step 1: Perform a level-order traversal of the binary tree using a queue.
  2. 2Step 2: For each level, calculate the sum of the node values.
  3. 3Step 3: Use a min-heap to keep track of the top k largest sums. If the size of the heap exceeds k, remove the smallest sum.
  4. 4Step 4: After processing all levels, if the heap has fewer than k elements, return -1; otherwise, return the root of the heap.
solution.py22 lines
1# Full working Python code
2import heapq
3from collections import deque
4
5def kthLargestLevelSum(root, k):
6    if not root:
7        return -1
8    level_sums = []
9    queue = deque([root])
10    while queue:
11        level_sum = 0
12        for _ in range(len(queue)):
13            node = queue.popleft()
14            level_sum += node.val
15            if node.left:
16                queue.append(node.left)
17            if node.right:
18                queue.append(node.right)
19        heapq.heappush(level_sums, level_sum)
20        if len(level_sums) > k:
21            heapq.heappop(level_sums)
22    return level_sums[0] if len(level_sums) == k else -1

Complexity note: The time complexity is O(n log k) because we process each node once and maintain a heap of size k, which takes log k time for each insertion. The space complexity is O(k) for storing the k largest sums.

  • 1Using a heap can significantly optimize the retrieval of the k-th largest element.
  • 2Level-order traversal is essential for calculating sums at each level.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.