Input: root =[5,8,9,2,1,3,7,4,6], k =2Output: 13Explanation: The level sums are the following:- Level 1:5.- Level 2:8+9=17.- Level 3:2+1+3+7=13.- Level 4:4+6=10.The 2nd largest level sum is13.
Example 2:
1
2
3
4
5
1/2/3
1
2
3
Input: root =[1,2,null,3], k =1Output: 3Explanation: The largest level sum is3.
To solve the problem, we can perform a level order traversal (BFS) of the binary tree to compute the sum of nodes at each level. We then keep track of these sums and, finally, find the kth largest sum.
Breadth-First Search (BFS): Use BFS to access nodes level by level.
Sum Calculation: For each level, calculate the sum of the node values.
Store Level Sums: Store the level sums in a list.
Find k-th Largest Sum: Sort the list of level sums in descending order and return the kth largest sum if it exists; otherwise, return -1.
publicclassSolution {
publiclongkthLargestLevelSum(TreeNode root, int k) {
// If the tree is empty, return -1if (root ==null) return-1;
// Initialize a queue for level-order traversal and a min heap to track the k largest levels Queue<TreeNode> queue =new LinkedList<>();
PriorityQueue<Long> minHeap =new PriorityQueue<>();
// Start with the root node in the queue queue.offer(root);
while (!queue.isEmpty()) {
// Get the number of nodes at the current levelint levelSize = queue.size();
// Initialize the sum for the current levellong levelSum = 0;
// Process each node at the current levelfor (int i = 0; i < levelSize; i++) {
// Poll the next node from the queue TreeNode curr = queue.poll();
// Add its value to the level sum levelSum += curr.val;
// If the current node has a left child, add it to the queueif (curr.left!=null) {
queue.offer(curr.left);
}
// If the current node has a right child, add it to the queueif (curr.right!=null) {
queue.offer(curr.right);
}
}
// Add the level sum to the min heap minHeap.offer(levelSum);
// If the heap size exceeds k, remove the smallest element to keep only the k largest sumsif (minHeap.size() > k) {
minHeap.poll();
}
}
// If the heap contains fewer than k elements, return -1; otherwise, return the k-th largest sumreturn minHeap.size() < k ?-1 : minHeap.peek();
}
}
The strategy will be to maintain a min heap of size k. As we encounter level sums, we add them to the heap. If the heap exceeds size k, we remove the smallest sum from heap.
The root of the heap will then be the kth largest element.