Sponsored
Sponsored
In this approach, we utilize Breadth-First Search (BFS) to traverse the binary tree level by level. As we traverse each level, we compute the sum of the node values at that level. We store these sums in a min-heap of size 'k'. If the heap grows beyond size 'k', we remove the smallest element, ensuring that at the end, the heap contains the 'k' largest level sums. This allows us to efficiently retrieve the kth largest level sum by looking at the top of the min-heap.
Time Complexity: O(n log k), where 'n' is the number of nodes in the tree. We traverse all nodes once, and each heap operation takes O(log k).
Space Complexity: O(max(w, k)), where 'w' is the maximum width of the tree at any level (for the queue), and 'k' is the size of the heap.
1#include <queue>
2#include <vector>
3#include <algorithm>
4
5using namespace std;
6
7struct TreeNode {
8 int val;
9 TreeNode *left;
10 TreeNode *right;
11 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
12};
13
14int kthLargestLevelSum(TreeNode* root, int k) {
15 if (!root) return -1;
16 queue<TreeNode*> q;
17 q.push(root);
18 priority_queue<int, vector<int>, greater<int>> minHeap;
19
20 while (!q.empty()) {
21 int levelSize = q.size();
22 int levelSum = 0;
23 for (int i = 0; i < levelSize; ++i) {
24 TreeNode* node = q.front();
25 q.pop();
26 levelSum += node->val;
27 if (node->left) q.push(node->left);
28 if (node->right) q.push(node->right);
29 }
30 minHeap.push(levelSum);
31 if (minHeap.size() > k) {
32 minHeap.pop();
33 }
34 }
35 return minHeap.size() == k ? minHeap.top() : -1;
36}
This C++ solution utilizes a queue to perform BFS over the binary tree, calculates the sum of each level, and employs a min-heap to maintain the 'k' largest sums.
This approach utilizes a depth-first search (DFS) technique with a modification that tracks and accumulates the sum values per level in an array or list. Once all levels are processed with DFS, we sort the resulting list of sums. If the list has fewer than 'k' entries, we return -1; otherwise, we return the k-th largest value by accessing the list.
Time Complexity: O(n + d log d), where 'n' is the number of nodes and 'd' is the depth of the tree (to sort the level sums).
Space Complexity: O(d), representing the recursion stack and array for level sums, where 'd' is tree depth.
1
This Python solution performs a DFS while maintaining a level-specific accumulation of sums. After complete traversal and sum computation, we sort and pick the k-th largest sum.