| | 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 | | namespace LeetCode.Algorithms.MinimumHeightTrees; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MinimumHeightTreesLeafPruning : IMinimumHeightTrees |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(V + E), where V is the number of vertices(nodes) and E is the number of edges. |
| | 19 | | /// Space complexity - O(V), where V is the number of vertices(nodes). |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <param name="edges"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public IList<int> FindMinHeightTrees(int n, int[][] edges) |
| 10 | 25 | | { |
| 10 | 26 | | if (n == 1) |
| 1 | 27 | | { |
| 1 | 28 | | return new List<int> { 0 }; |
| | 29 | | } |
| | 30 | |
|
| 9 | 31 | | var graph = new List<HashSet<int>>(); |
| | 32 | |
|
| 118 | 33 | | for (var i = 0; i < n; i++) |
| 50 | 34 | | { |
| 50 | 35 | | graph.Add([]); |
| 50 | 36 | | } |
| | 37 | |
|
| 109 | 38 | | foreach (var edge in edges) |
| 41 | 39 | | { |
| 41 | 40 | | graph[edge[0]].Add(edge[1]); |
| 41 | 41 | | graph[edge[1]].Add(edge[0]); |
| 41 | 42 | | } |
| | 43 | |
|
| 9 | 44 | | var leaves = new List<int>(); |
| | 45 | |
|
| 118 | 46 | | for (var i = 0; i < n; i++) |
| 50 | 47 | | { |
| 50 | 48 | | if (graph[i].Count == 1) |
| 27 | 49 | | { |
| 27 | 50 | | leaves.Add(i); |
| 27 | 51 | | } |
| 50 | 52 | | } |
| | 53 | |
|
| 9 | 54 | | var remainingNodes = n; |
| | 55 | |
|
| 22 | 56 | | while (remainingNodes > 2) |
| 13 | 57 | | { |
| 13 | 58 | | remainingNodes -= leaves.Count; |
| | 59 | |
|
| 13 | 60 | | var newLeaves = new List<int>(); |
| | 61 | |
|
| 109 | 62 | | foreach (var leaf in leaves) |
| 35 | 63 | | { |
| 35 | 64 | | var neighbor = graph[leaf].First(); |
| | 65 | |
|
| 35 | 66 | | graph[neighbor].Remove(leaf); |
| | 67 | |
|
| 35 | 68 | | if (graph[neighbor].Count == 1) |
| 23 | 69 | | { |
| 23 | 70 | | newLeaves.Add(neighbor); |
| 23 | 71 | | } |
| 35 | 72 | | } |
| | 73 | |
|
| 13 | 74 | | leaves = newLeaves; |
| 13 | 75 | | } |
| | 76 | |
|
| 9 | 77 | | return leaves; |
| 10 | 78 | | } |
| | 79 | | } |