Advertisement
1988coder

310. Minimum Height Trees

Dec 23rd, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. /*
  2. Refer: https://leetcode.com/problems/minimum-height-trees/discuss/76055/Share-some-thoughts
  3. Time Complexity: O(N)
  4. Space Complexity: O(N)
  5.  
  6. N = number of vertices
  7. */
  8. class Solution {
  9.     public List<Integer> findMinHeightTrees(int n, int[][] edges) {
  10.         if (n < 1) {
  11.             return new ArrayList<Integer>();
  12.         }
  13.         if (n == 1) {
  14.             return new ArrayList<Integer>(Arrays.asList(0));
  15.         }
  16.        
  17.         Map<Integer, Set<Integer>> adjacencyMap = new HashMap();
  18.         for (int i = 0; i < n; i++) {
  19.             adjacencyMap.put(i, new HashSet<Integer>());
  20.         }
  21.         for (int[] edge: edges) {
  22.             adjacencyMap.get(edge[0]).add(edge[1]);
  23.             adjacencyMap.get(edge[1]).add(edge[0]);
  24.         }
  25.        
  26.         Queue<Integer> queue = new LinkedList();
  27.         for (int i = 0; i < n; i++) {
  28.             if (adjacencyMap.get(i).size() == 1) {
  29.                 queue.offer(i);
  30.             }
  31.         }
  32.        
  33.         while (n > 2) {
  34.             int queueSize = queue.size();
  35.             n -= queueSize;
  36.             while (queueSize > 0) {
  37.                 int leaf = queue.poll();
  38.                 int neighbour = adjacencyMap.get(leaf).iterator().next();
  39.                 adjacencyMap.get(neighbour).remove(leaf);
  40.                 if (adjacencyMap.get(neighbour).size() == 1) {
  41.                     queue.offer(neighbour);
  42.                 }
  43.                 queueSize--;
  44.             }
  45.         }
  46.        
  47.         return new ArrayList<Integer>(queue);
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement