In this Leetcode Minimum Height Trees problem solution 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.

Leetcode Minimum Height Trees problem solution


Problem solution in Python.

def findMinHeightTrees(n: int, edges: List[List[int]]) -> List[int]:
        graph = [set() for _ in range(n)]
        
        for u, v in edges:
            graph[u].add(v)
            graph[v].add(u)

        leaves = [x for x in range(n) if len(graph[x]) <= 1]
        prev_leaves = leaves
        while leaves:
            new_leaves = []
            for leaf in leaves:
                if not graph[leaf]:
                    return leaves
                neighbor = graph[leaf].pop()
                graph[neighbor].remove(leaf)
                if len(graph[neighbor]) == 1:
                    new_leaves.append(neighbor)
            prev_leaves, leaves = leaves, new_leaves

        return prev_leaves



Problem solution in Java.

class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> list1 = new ArrayList<>();
        if(n == 0) // base case1
            return list1;
        if(n == 1) // base case2
        {
            list1.add(0);
            return list1;
        }
        List<HashSet<Integer>> adjlist = new ArrayList<HashSet<Integer>>();
        for(int i=0;i<n;i++) // create all n numbers of hashSet
        {
            adjlist.add(new HashSet<Integer>());
        }
        for(int edge[] : edges) // make the graph virtually
        {
            adjlist.get(edge[0]).add(edge[1]);
            adjlist.get(edge[1]).add(edge[0]);
        }
        List<Integer> leaves = new ArrayList<>();
        for(int i=0;i<n;i++) // select the initial leaves
        {
            if(adjlist.get(i).size() == 1)
            {
                leaves.add(i);
            }
        }
        while(n > 2)
        {
            n = n - leaves.size();
            List<Integer> newleaves = new ArrayList<>();
            for(int leaf : leaves)
            {
                int neighbour = adjlist.get(leaf).iterator().next();
                adjlist.get(neighbour).remove(leaf);
                if(adjlist.get(neighbour).size() == 1)
                {
                    newleaves.add(neighbour);
                }
            }
            leaves = newleaves;
        }
        
        return leaves;
    }
}


Problem solution in C++.

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges)
    {
        vector<int> leaves;
        vector<vector<int>> graph(n,vector<int>());
        
        for(auto ed : edges)
        {
            graph[ed[0]].push_back(ed[1]);
            graph[ed[1]].push_back(ed[0]);
        }
        //Prepare the list of leaves to remove
        for(int i=0;i<n;i++)
        {
            if(graph[i].size()==1)
                leaves.push_back(i);
        }
        while(n>2)
        {
            n-=leaves.size();
            vector<int> new_leaves;
            for(auto leaf : leaves)
            {
                int adj = graph[leaf][0];
                vector<int>::iterator itr = remove(graph[adj].begin(),graph[adj].end(),leaf);
                graph[adj].erase(itr,graph[adj].end());
                if(graph[adj].size()==1)
                    new_leaves.push_back(adj);
            }
            leaves = new_leaves;
        }
        if(leaves.size()==0)
            return {0};
        return leaves;
    }
};