Leetcode Minimum Height Trees problem solution

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.

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:

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
{
return list1;
}
for(int i=0;i<n;i++) // create all n numbers of hashSet
{
}
for(int edge[] : edges) // make the graph virtually
{
}
List<Integer> leaves = new ArrayList<>();
for(int i=0;i<n;i++) // select the initial leaves
{
{
}
}
while(n > 2)
{
n = n - leaves.size();
List<Integer> newleaves = new ArrayList<>();
for(int leaf : leaves)
{
{
}
}
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)
{
}
leaves = new_leaves;
}
if(leaves.size()==0)
return {0};
return leaves;
}
};

```