Kth Largest Sum in a Binary Tree (LeetCode 2583): Solution and Explanation

Medium
Tree
Breadth First Search
Sorting
Binary Tree

Add up the values on each level of a binary tree, then return the k-th largest of those level sums. If the tree has fewer than k levels, return -1.

Intuition

A level sum only needs the nodes of one level, and a breadth-first search hands you exactly one level at a time.

Once every level has a single number, the tree no longer matters. The question becomes: what is the k-th largest number in a short list?

The list has one entry per level, so it is usually far smaller than n. Sorting it is cheap, and it also tells you directly whether k is out of range.

Approach: Level order sums, then sort

  1. Start with level = [root] and an empty list sums.
  2. While the level is not empty, append the sum of its values to sums and build the next level from the children.
  3. If k is larger than len(sums), return -1.
  4. Sort sums from largest to smallest and return sums[k - 1].
  5. Keep every sum in a 64-bit type: a level can hold many values up to 10^6 and pass 2^31.

Step-by-step example

root = [5,8,9,2,1,3,7,4,6], k = 2
  1. Level 0 holds 5, so its sum is 5.
  2. Level 1 holds 8 and 9, so its sum is 17.
  3. Level 2 holds 2, 1, 3 and 7, so its sum is 13. Level 3 holds 4 and 6, so its sum is 10.
  4. There are 4 levels and k = 2, so an answer exists. Sorted from largest: 17, 13, 10, 5.
  5. The 2nd entry is 13. Return 13.

Code: Python, Java, C++

1class Solution:
2    def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
3        sums = []
4        level = [root]
5        while level:
6            sums.append(sum(node.val for node in level))
7            level = [c for node in level for c in (node.left, node.right) if c]
8        if k > len(sums):
9            return -1
10        sums.sort(reverse=True)
11        return sums[k - 1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + L log L)

The traversal touches each node once. Sorting the L level sums costs L log L, and L is at most n.

Space

O(n)

The widest level can hold about n / 2 nodes, and the sums list holds L numbers.

Other approaches

Min-heap of size k (time O(n + L log k), space O(n))

Push each level sum into a min-heap and pop whenever it grows past k. After the traversal the heap top is the k-th largest. Helps when there are many levels and k is small.

DFS with a depth-indexed array (time O(n + L log L), space O(n))

Walk the tree depth first, adding each value to sums[depth]. Same sums as BFS, but the recursion can reach depth n on a skewed tree.

Common mistakes

  • Using a 32-bit int for the sums. A level of a few thousand nodes worth 10^6 each already passes 2^31, so Java, C++, C# and Go need long or int64.
  • Treating equal sums as one value. The k-th largest is not necessarily distinct, so two levels with the same sum take two places.
  • Forgetting the -1 case when k is larger than the number of levels.

Frequently asked questions

Why sort instead of using a heap?

The number of levels is usually small, so sorting it is simple and fast. A size-k min-heap is the better choice when there are many levels and k is small.

Does a depth-first search work too?

Yes. Pass the depth down and add each node's value to sums[depth]. It produces the same list, just in a different visiting order.

Why does the function return long in Java?

A single level sum can exceed the 32-bit range, so the answer itself must be 64-bit.