-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
27 lines (26 loc) · 792 Bytes
/
Solution.cs
File metadata and controls
27 lines (26 loc) · 792 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution
{
public long KthLargestLevelSum(TreeNode root, int k)
{
if (root is null) return -1;
Queue<TreeNode> queue = [];
List<long> sumLevel = [];
queue.Enqueue(root);
while (queue.Count > 0)
{
int length = queue.Count;
long sum = 0;
for (int i = 0; i < length; i++)
{
var node = queue.Dequeue();
sum += node.val;
if (node.left is not null) queue.Enqueue(node.left);
if (node.right is not null) queue.Enqueue(node.right);
}
sumLevel.Add(sum);
}
if (k > sumLevel.Count) return -1;
sumLevel.Sort((a, b) => b.CompareTo(a));
return sumLevel[k - 1];
}
}