28 lines
625 B
C#
28 lines
625 B
C#
|
public class Solution {
|
||
|
private void Sum(List<long> levels, TreeNode node, int level) {
|
||
|
if (node == null) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
while (level >= levels.Count) {
|
||
|
levels.Add(0);
|
||
|
}
|
||
|
|
||
|
levels[level] += node.val;
|
||
|
Sum(levels, node.left, level + 1);
|
||
|
Sum(levels, node.right, level + 1);
|
||
|
}
|
||
|
|
||
|
public long KthLargestLevelSum(TreeNode root, int k) {
|
||
|
var levels = new List<long>();
|
||
|
|
||
|
Sum(levels, root, 0);
|
||
|
if (k > levels.Count) {
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
levels.Sort();
|
||
|
return levels[levels.Count - k];
|
||
|
}
|
||
|
}
|