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.
1from heapq import heappush, heappop
2from collections import deque
3
4def kth_largest_level_sum(root, k):
5 if not root:
6 return -1
7
8 queue = deque([root])
9 min_heap = []
10
11 while queue:
12 level_size = len(queue)
13 current_level_sum = 0
14
15 for _ in range(level_size):
16 node = queue.popleft()
17 current_level_sum += node.val
18 if node.left:
19 queue.append(node.left)
20 if node.right:
21 queue.append(node.right)
22
23 heappush(min_heap, current_level_sum)
24 if len(min_heap) > k:
25 heappop(min_heap)
26
27 return min_heap[0] if len(min_heap) == k else -1
This Python solution uses BFS to iterate over each level of the tree, computes the sum of each level, and maintains the 'k' largest sums using a min-heap.
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.
1using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
public int KthLargestLevelSum(TreeNode root, int k) {
List<int> levelSums = new List<int>();
Dfs(root, 0, levelSums);
if (levelSums.Count < k) return -1;
levelSums.Sort((a, b) => b.CompareTo(a));
return levelSums[k - 1];
}
private void Dfs(TreeNode node, int level, List<int> levelSums) {
if (node == null) return;
if (level == levelSums.Count) levelSums.Add(0);
levelSums[level] += node.val;
Dfs(node.left, level + 1, levelSums);
Dfs(node.right, level + 1, levelSums);
}
}
C# implementation involves using DFS to compute sums at each tree level and sorting these sums to acquire the k-th highest sum result.