Minimum Height Trees - LeetCode 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. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Example 1:
Input: n = 4, edges = [[1,0],[1,2],[1,3]] Output: [1] Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. Example 2:
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] Output: [3,4] Example 3: Input: n = 1, edges = [] Output: [0] Example 4: Input: n = 2, edges = [[0,1]] Output: [0,1]
Constraints:
1 <= n <= 2 * 104 edges.length == n - 1 0 <= ai, bi < n ai != bi All the pairs (ai, bi) are distinct. The given input is guaranteed to be a tree and there will be no repeated edges.
- code
class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
// base cases
if (n <= 2) {
ArrayList<Integer> centroids = new ArrayList<>();
for (int i = 0; i < n; i++)
centroids.add(i);
return centroids;
}
// Build the graph with the adjacency list
List<List<Integer>> neighbors = new ArrayList<>();
for (int i = 0; i < n; i++)
neighbors.add(new ArrayList<Integer>());
for (int[] edge : edges) {
int start = edge[0], end = edge[1];
neighbors.get(start).add(end);
neighbors.get(end).add(start);
}
// Initialize the first layer of leaves
ArrayList<Integer> leaves = new ArrayList<>();
for (int i = 0; i < n; i++)
if (neighbors.get(i).size() == 1)
leaves.add(i);
// Trim the leaves until reaching the centroids
int remainingNodes = n;
while (remainingNodes > 2) {
remainingNodes -= leaves.size();
ArrayList<Integer> newLeaves = new ArrayList<>();
// remove the current leaves along with the edges
for (Integer leaf : leaves) {
// the only neighbor left for the leaf node
// Integer neighbor = neighbors.get(leaf).iterator().next();
Integer neighbor = neighbors.get(leaf).get(0);
// remove the edge along with the leaf node
neighbors.get(neighbor).remove(leaf);
if (neighbors.get(neighbor).size() == 1)
newLeaves.add(neighbor);
}
// prepare for the next round
leaves = newLeaves;
}
// The remaining nodes are the centroids of the graph
return leaves;
}
}
- code
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n <= 2: return list(range(n))
adja = [[] for i in range(n)]
for i, j in edges:
adja[i].append(j)
adja[j].append(i)
leaves = [] # outmost
for node, nei in enumerate(adja):
if len(nei) == 1:
leaves.append(node)
nodeleft = n
while nodeleft > 2:
# remove leaves
nodeleft -= len(leaves)
newleaves = []
while leaves:
cur = leaves.pop()
only_nei = adja[cur].pop() # cur leaf's only nei
adja[only_nei].remove(cur)
if len(adja[only_nei]) == 1:
newleaves.append(only_nei)
leaves = newleaves
return leaves
Topological sorting - Wikipedia
- code TLE
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
adja = defaultdict(list)
for i, j in edges:
adja[i].append(j)
adja[j].append(i)
minheight = inf
ans = []
for node in range(n):
curheight = -1
visited = set()
q = deque([node])
visited.add(node)
finished = True
while q:
curheight += 1
if curheight > minheight:
finished = False
break
for _ in range(len(q)):
cur = q.popleft()
for nei in adja[cur]:
if nei not in visited:
q.append(nei)
visited.add(nei)
if finished:
if curheight == minheight:
ans.append(node)
elif curheight < minheight:
minheight = curheight
ans = [node]
return ans