From 18e176c3e67ab92610e60c4c87a4fc3181a1fdba Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 22 Oct 2024 22:22:44 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB2583.=20Kth=20Largest=20Sum?= =?UTF-8?q?=20in=20a=20Binary=20Tree=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/ Signed-off-by: Matej Focko --- cs/kth-largest-sum-in-a-binary-tree.cs | 27 ++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 cs/kth-largest-sum-in-a-binary-tree.cs diff --git a/cs/kth-largest-sum-in-a-binary-tree.cs b/cs/kth-largest-sum-in-a-binary-tree.cs new file mode 100644 index 0000000..c0a11cd --- /dev/null +++ b/cs/kth-largest-sum-in-a-binary-tree.cs @@ -0,0 +1,27 @@ +public class Solution { + private void Sum(List 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(); + + Sum(levels, root, 0); + if (k > levels.Count) { + return -1; + } + + levels.Sort(); + return levels[levels.Count - k]; + } +}