[LeetCode][JavaScript]Minimum Height Trees
Minimum Height Trees
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.
Format
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).
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
.
Example 1:
Given n = 4
, edges = [[1, 0], [1, 2], [1, 3]]
0 | 1 / \ 2 3
return [1]
Example 2:
Given n = 6
, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2 \ | / 3 | 4 | 5
return [3, 4]
https://leetcode.com/problems/minimum-height-trees/
题意是以任意的节点为root,求出最高的那棵树。
可以转化为求从叶子到叶子最长的路径的中心,结果只可能是一个或者两个。
建立树,bfs遍历,每一轮都去掉所有的叶子节点,最后留下的就是结果。
开一个变量visited记录遍历过点的数量,如果visited >= n -2说明找到结果了。
1 /** 2 * @param {number} n 3 * @param {number[][]} edges 4 * @return {number[]} 5 */ 6 var findMinHeightTrees = function(n, edges) { 7 if(n === 1) return [0]; 8 var result = [], tree = {}, list = [], i, j, curr, visited = 0; 9 for(i = 0; i < edges.length; i++){ 10 curr = edges[i]; 11 if(!tree[curr[0]]) tree[curr[0]] = new Node(curr[0]); 12 if(!tree[curr[1]]) tree[curr[1]] = new Node(curr[1]); 13 tree[curr[0]].neighbor.push(tree[curr[1]]); 14 tree[curr[1]].neighbor.push(tree[curr[0]]); 15 } 16 for(i in tree){ 17 if(tree[i].neighbor.length === 1){ 18 list.push(tree[i].val); 19 } 20 } 21 bfs(list); 22 for(i = 0; i < list.length; i++){ 23 result.push(list[i]); 24 } 25 return result; 26 27 function Node(val){ 28 this.val = val; 29 this.neighbor = []; 30 } 31 function bfs(list){ 32 var len = list.length, top, topNeighbor; 33 if(visited >= n - 2) return; 34 while(len--){ 35 visited++; 36 top = tree[list.shift()]; 37 topNeighbor = top.neighbor[0]; 38 deleteNode(topNeighbor.neighbor, top.val); 39 if(topNeighbor.neighbor.length <= 1 && list.indexOf(topNeighbor.val) === -1){ 40 list.push(topNeighbor.val); 41 } 42 delete tree[top.val]; 43 } 44 bfs(list); 45 } 46 function deleteNode(arr, val){ 47 for(var i = 0; i < arr.length; i++){ 48 if(arr[i].val === val){ 49 arr.splice(i,1); 50 return; 51 } 52 } 53 } 54 };