cs: add «2583. Kth Largest Sum in a Binary Tree»
URL: https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
916067a73a
commit
18e176c3e6
1 changed files with 27 additions and 0 deletions
27
cs/kth-largest-sum-in-a-binary-tree.cs
Normal file
27
cs/kth-largest-sum-in-a-binary-tree.cs
Normal file
|
@ -0,0 +1,27 @@
|
|||
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];
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue