1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| func findMinHeightTrees(n int, edges [][]int) []int { if n == 1 { return []int{0} } relations := make([][]int, n) inCount := make([]int, n) for _, edge := range edges { relations[edge[0]] = append(relations[edge[0]], edge[1]) relations[edge[1]] = append(relations[edge[1]], edge[0]) inCount[edge[0]]++ inCount[edge[1]]++ } queue := []int{} for i, count := range inCount { if count == 1 { queue = append(queue, i) } } ans := queue for len(queue) > 0 { ans = queue size := len(queue) for i := 0; i < size; i++ { for _, node := range relations[queue[i]] { inCount[node]-- if inCount[node] == 1 { queue = append(queue, node) } } } queue = queue[size:] } return ans }
|