|
| 1 | +/** |
| 2 | + * 310. Minimum Height Trees |
| 3 | + * https://leetcode.com/problems/minimum-height-trees/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A tree is an undirected graph in which any two vertices are connected by exactly one |
| 7 | + * path. In other words, any connected graph without simple cycles is a tree. |
| 8 | + * |
| 9 | + * Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where |
| 10 | + * edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes |
| 11 | + * ai and bi in the tree, you can choose any node of the tree as the root. When you select |
| 12 | + * a node x as the root, the result tree has height h. Among all possible rooted trees, |
| 13 | + * those with minimum height (i.e. min(h)) are called minimum height trees (MHTs). |
| 14 | + * |
| 15 | + * Return a list of all MHTs' root labels. You can return the answer in any order. |
| 16 | + * |
| 17 | + * The height of a rooted tree is the number of edges on the longest downward path |
| 18 | + * between the root and a leaf. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number} n |
| 23 | + * @param {number[][]} edges |
| 24 | + * @return {number[]} |
| 25 | + */ |
| 26 | +var findMinHeightTrees = function(n, edges) { |
| 27 | + if (n === 1) return [0]; |
| 28 | + |
| 29 | + const lookup = new Array(n).fill().map(() => new Set()); |
| 30 | + for (const [a, b] of edges) { |
| 31 | + lookup[a].add(b); |
| 32 | + lookup[b].add(a); |
| 33 | + } |
| 34 | + |
| 35 | + let result = []; |
| 36 | + for (let i = 0; i < n; i++) { |
| 37 | + if (lookup[i].size === 1) result.push(i); |
| 38 | + } |
| 39 | + |
| 40 | + while (n > 2) { |
| 41 | + n -= result.length; |
| 42 | + const modified = []; |
| 43 | + for (const item of result) { |
| 44 | + const adj = lookup[item].values().next().value; |
| 45 | + lookup[adj].delete(item); |
| 46 | + if (lookup[adj].size === 1) { |
| 47 | + modified.push(adj); |
| 48 | + } |
| 49 | + } |
| 50 | + result = modified; |
| 51 | + } |
| 52 | + |
| 53 | + return result; |
| 54 | +}; |
0 commit comments