Kth Largest Sum in a Binary Tree (LeetCode 2583): Solution and Explanation
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
- Start with
level = [root]and an empty listsums. - While the level is not empty, append the sum of its values to
sumsand build the next level from the children. - If
kis larger thanlen(sums), return -1. - Sort
sumsfrom largest to smallest and returnsums[k - 1]. - 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
- Level 0 holds 5, so its sum is 5.
- Level 1 holds 8 and 9, so its sum is 17.
- Level 2 holds 2, 1, 3 and 7, so its sum is 13. Level 3 holds 4 and 6, so its sum is 10.
- There are 4 levels and k = 2, so an answer exists. Sorted from largest: 17, 13, 10, 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]1class Solution {
2 public long kthLargestLevelSum(TreeNode root, int k) {
3 List<Long> sums = new ArrayList<>();
4 Queue<TreeNode> queue = new ArrayDeque<>();
5 queue.offer(root);
6 while (!queue.isEmpty()) {
7 long total = 0;
8 for (int i = queue.size(); i > 0; i--) {
9 TreeNode node = queue.poll();
10 total += node.val;
11 if (node.left != null) queue.offer(node.left);
12 if (node.right != null) queue.offer(node.right);
13 }
14 sums.add(total);
15 }
16 if (k > sums.size()) return -1;
17 sums.sort(Collections.reverseOrder());
18 return sums.get(k - 1);
19 }
20}1class Solution {
2public:
3 long long kthLargestLevelSum(TreeNode* root, int k) {
4 vector<long long> sums;
5 queue<TreeNode*> q;
6 q.push(root);
7 while (!q.empty()) {
8 long long total = 0;
9 for (int i = q.size(); i > 0; i--) {
10 TreeNode* node = q.front();
11 q.pop();
12 total += node->val;
13 if (node->left) q.push(node->left);
14 if (node->right) q.push(node->right);
15 }
16 sums.push_back(total);
17 }
18 if (k > (int) sums.size()) return -1;
19 sort(sums.rbegin(), sums.rend());
20 return sums[k - 1];
21 }
22};Time and space complexity
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.
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.