| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.KthLargestSumInBinaryTree; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class KthLargestSumInBinaryTreeBreadthFirstSearch : IKthLargestSumInBinaryTree |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n log k) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <param name="k"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public long KthLargestLevelSum(TreeNode root, int k) |
| 2 | 27 | | { |
| 2 | 28 | | var nodesQueue = new Queue<TreeNode>(); |
| | 29 | |
|
| 2 | 30 | | nodesQueue.Enqueue(root); |
| | 31 | |
|
| 2 | 32 | | var sumsPriorityQueue = new PriorityQueue<long, long>(); |
| | 33 | |
|
| 9 | 34 | | while (nodesQueue.Count > 0) |
| 7 | 35 | | { |
| 7 | 36 | | var levelCount = nodesQueue.Count; |
| | 37 | |
|
| 7 | 38 | | long sum = 0; |
| | 39 | |
|
| 38 | 40 | | for (var j = 0; j < levelCount; j++) |
| 12 | 41 | | { |
| 12 | 42 | | var node = nodesQueue.Dequeue(); |
| | 43 | |
|
| 12 | 44 | | sum += node.val; |
| | 45 | |
|
| 12 | 46 | | if (node.left != null) |
| 6 | 47 | | { |
| 6 | 48 | | nodesQueue.Enqueue(node.left); |
| 6 | 49 | | } |
| | 50 | |
|
| 12 | 51 | | if (node.right != null) |
| 4 | 52 | | { |
| 4 | 53 | | nodesQueue.Enqueue(node.right); |
| 4 | 54 | | } |
| 12 | 55 | | } |
| | 56 | |
|
| 7 | 57 | | sumsPriorityQueue.Enqueue(sum, sum); |
| | 58 | |
|
| 7 | 59 | | if (sumsPriorityQueue.Count > k) |
| 4 | 60 | | { |
| 4 | 61 | | sumsPriorityQueue.Dequeue(); |
| 4 | 62 | | } |
| 7 | 63 | | } |
| | 64 | |
|
| 2 | 65 | | if (sumsPriorityQueue.Count < k) |
| 0 | 66 | | { |
| 0 | 67 | | return -1; |
| | 68 | | } |
| | 69 | |
|
| 2 | 70 | | return sumsPriorityQueue.Dequeue(); |
| 2 | 71 | | } |
| | 72 | | } |