From 712bf8e11a26c89fa387af0abcc0120b684714bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Khoa=20Hu=E1=BB=B3nh=20=28Daniel=29?= Date: Tue, 23 Apr 2024 23:49:40 +0700 Subject: [PATCH] Create main.go --- solution/310/main.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 solution/310/main.go diff --git a/solution/310/main.go b/solution/310/main.go new file mode 100644 index 0000000..27d13d4 --- /dev/null +++ b/solution/310/main.go @@ -0,0 +1,40 @@ +package main + +func findMinHeightTrees(n int, edges [][]int) []int { + if n == 1 { + return []int{0} + } + + adjList := make([][]int, n) + for _, edge := range edges { + adjList[edge[0]] = append(adjList[edge[0]], edge[1]) + adjList[edge[1]] = append(adjList[edge[1]], edge[0]) + } + + leaves := make([]int, 0) + for i := 0; i < n; i++ { + if len(adjList[i]) == 1 { + leaves = append(leaves, i) + } + } + + for n > 2 { + newLeaves := make([]int, 0) + for _, leaf := range leaves { + neighbor := adjList[leaf][0] + for i, node := range adjList[neighbor] { + if node == leaf { + adjList[neighbor] = append(adjList[neighbor][:i], adjList[neighbor][i+1:]...) + break + } + } + if len(adjList[neighbor]) == 1 { + newLeaves = append(newLeaves, neighbor) + } + n-- + } + leaves = newLeaves + } + + return leaves +}