/** 310. Minimum Height Trees * 2016-3-29 by Mingyang * Same method for constructing the graph without direction * Here is the use of a layer of stripping the way, one layer at a layer, to remove the * * My first thought of the solution is to traverse the point, in each Point all as the root node, calculate the height, and then find the smallest, found that the method is similar to the method of stripping onions, * is a layer of the faded leaf node, the last one or two nodes is the minimum height we require the root node of the tree, this idea is very ingenious, and it is not difficult to achieve, * with the previous Well, as in the course list, we need to create a graph G, which is a two-dimensional array, where g[i] is a one-dimensional array that holds all the nodes that I can reach. * A one-dimensional array d is also required to hold the entry information for each node, where D[i] represents the in-degree of the I-node. Our goal is to delete all of the leaf nodes, the leaf node into the degree of 1, * so we start to all into a 1 of the nodes (leaf nodes) are deposited into a queue of queues, and then we traverse each leaf node, through the graph to find and its connected node, * The node's penetration is reduced by 1, if the node's penetration is reduced to , which means that this node also becomes a leaf node, joins the queue, and then the next round is deleted. So what time do we delete, * when the number of nodes is less than or equal to 2 stops, then one or two of the remaining nodes is the root node of the minimum height tree we require .*/ PublicList<integer> Findminheighttrees (intNint[] edges) { if(n = = 1)returnCollections.singletonlist (0); List<Set<Integer>> adj =NewArraylist<set<integer>>(n); for(inti = 0; I < n; ++i) Adj.add (NewHashset<integer>()); for(int[] edge:edges) {Adj.get (edge[0]). Add (edge[1]); Adj.get (edge[1]). Add (edge[0]); } List<Integer> leaves =NewArraylist<integer>(); for(inti = 0; I < n; ++i)if(Adj.get (i). Size () = = 1) Leaves.add (i); //here is the leaf node, each leaf node on the top of the node, cut off the way back while(N > 2) {n-=leaves.size (); List<Integer> newleaves =NewArraylist<integer>(); for(inti:leaves) { intj =Adj.get (i). iterator (). Next (); Adj.get (j). Remove (i); if(Adj.get (j). Size () = = 1) Newleaves.add (j); } Leaves=newleaves; } returnleaves; }
310. Minimum Height Trees