|
| 1 | +package com.interview.graph; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Date 03/08/2016 |
| 7 | + * @author Tushar Roy |
| 8 | + * |
| 9 | + * Given a graph representing a tree. Find all minimum height trees. |
| 10 | + * |
| 11 | + * Time complexity O(n) |
| 12 | + * Space complexity O(n) |
| 13 | + * |
| 14 | + * https://leetcode.com/problems/minimum-height-trees/ |
| 15 | + */ |
| 16 | +public class MininumHeightTree { |
| 17 | + public List<Integer> findMinHeightTrees(int n, int[][] edges) { |
| 18 | + if (n == 1) { |
| 19 | + return Collections.singletonList(0); |
| 20 | + } |
| 21 | + List<Set<Integer>> adj = new ArrayList<>(); |
| 22 | + for (int i = 0; i < n; i++) { |
| 23 | + adj.add(new HashSet<>()); |
| 24 | + } |
| 25 | + for (int[] edge: edges) { |
| 26 | + adj.get(edge[0]).add(edge[1]); |
| 27 | + adj.get(edge[1]).add(edge[0]); |
| 28 | + } |
| 29 | + |
| 30 | + List<Integer> leaves = new ArrayList<>(); |
| 31 | + for (int i = 0; i < n; i++) { |
| 32 | + if (adj.get(i).size() == 1) { |
| 33 | + leaves.add(i); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + while (n > 2) { |
| 38 | + n -= leaves.size(); |
| 39 | + List<Integer> newLeaves = new ArrayList<>(); |
| 40 | + for (int leaf : leaves) { |
| 41 | + int node = adj.get(leaf).iterator().next(); |
| 42 | + adj.get(node).remove(leaf); |
| 43 | + if (adj.get(node).size() == 1) { |
| 44 | + newLeaves.add(node); |
| 45 | + } |
| 46 | + } |
| 47 | + leaves = newLeaves; |
| 48 | + } |
| 49 | + |
| 50 | + return leaves; |
| 51 | + } |
| 52 | + |
| 53 | + public static void main(String args[]) { |
| 54 | + MininumHeightTree mht = new MininumHeightTree(); |
| 55 | + int input[][] = {{1,0},{1,2},{1,3}}; |
| 56 | + List<Integer> result = mht.findMinHeightTrees(4, input); |
| 57 | + result.forEach(r -> System.out.print(r + " ")); |
| 58 | + } |
| 59 | +} |
0 commit comments