|
| 1 | +/** |
| 2 | + * res.js |
| 3 | + *@authors Joe Jiang (hijiangtao@gmail.com) |
| 4 | + *@date 2017-04-17 14:02:24 |
| 5 | + * |
| 6 | + * For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. |
| 7 | + * |
| 8 | + * Format |
| 9 | + * The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels). |
| 10 | + * |
| 11 | + * You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. |
| 12 | + * |
| 13 | + * Note: |
| 14 | + * |
| 15 | + * (1) According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.” |
| 16 | + * |
| 17 | + * (2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. |
| 18 | + * |
| 19 | + *@param {number} n |
| 20 | + *@param {number[][]} edges |
| 21 | + *@return {number[]} |
| 22 | + */ |
| 23 | +letfindMinHeightTrees=function(n,edges){ |
| 24 | +letelen=edges.length,// 边数长度 |
| 25 | +nlist=[],// 节点列表 |
| 26 | +deglist=[],//度数列表 |
| 27 | +adj=newArray(n);//存储连边信息 |
| 28 | + |
| 29 | +for(leti=0;i<n;i++){ |
| 30 | +nlist.push(i); |
| 31 | +deglist.push(0); |
| 32 | +adj[i]=newSet(); |
| 33 | +} |
| 34 | +for(leti=0;i<elen;i++){ |
| 35 | +letsource=edges[i][0], |
| 36 | +target=edges[i][1]; |
| 37 | + |
| 38 | +adj[source].add(target); |
| 39 | +adj[target].add(source); |
| 40 | +deglist[source]++; |
| 41 | +deglist[target]++; |
| 42 | +} |
| 43 | + |
| 44 | +// 结果中只能是一个元素或者两个元素, 或者全部元素 (如果有多个树结构) |
| 45 | +while(nlist.length>2){ |
| 46 | +letlenNow=nlist.length, |
| 47 | +dellist=[]; |
| 48 | + |
| 49 | +for(leti=0;i<lenNow;i++){ |
| 50 | +letnode=nlist[i]; |
| 51 | +if(!deglist[node]){ |
| 52 | +//当前节点边数为0 |
| 53 | +nlist.splice(i--,1); |
| 54 | +lenNow--; |
| 55 | +}elseif(deglist[node]===1){ |
| 56 | +//删除边并减少两端节点的degree |
| 57 | +letanothernode=-1; |
| 58 | +for(letj=0;j<lenNow;j++){ |
| 59 | +if(i===j)continue; |
| 60 | +if(adj[node].has(nlist[j])){ |
| 61 | +anothernode=nlist[j]; |
| 62 | +break; |
| 63 | +} |
| 64 | +} |
| 65 | +adj[node].delete(anothernode); |
| 66 | +adj[anothernode].delete(node); |
| 67 | +dellist.push(anothernode); |
| 68 | +deglist[node]=0; |
| 69 | +nlist.splice(i--,1); |
| 70 | +lenNow--; |
| 71 | +} |
| 72 | +} |
| 73 | + |
| 74 | +for(leti=dellist.length-1;i>=0;i--){ |
| 75 | +deglist[dellist[i]]--; |
| 76 | +} |
| 77 | +} |
| 78 | + |
| 79 | +returnnlist; |
| 80 | +}; |