Problem Description
Given the root of a binary tree and a positive integer k, the task is to compute the sum of node values for each level in the tree. Then, return the kth largest level sum (levels are counted from root, and kth largest implies ordering the sums in descending order). If the number of levels is less than k, return -1.
Key Insights
- We use a Breadth-first Search (BFS) to traverse the tree level by level.
- For each level, compute the sum of all node values.
- Collect all level sums, and then sort them in descending order to pick the kth largest sum.
- Edge case: if the tree has fewer than k levels, then return -1.
Space and Time Complexity
Time Complexity: O(n log n) in the worst-case scenario (when the tree is skewed so that there are O(n) levels and sorting these level sums takes O(n log n)). Space Complexity: O(n) for storing the level sums and using a queue during the BFS.
Solution
The solution begins by performing a level-order (BFS) traversal of the tree. During each level of the traversal, all nodes are processed and their values summed up. These sums are stored in a list. Once the traversal is complete, the list of sums is sorted in descending order. The kth largest element is then accessed from this sorted list. If k exceeds the number of levels present, the function returns -1.