Minimum Height Trees - LeetCode Daily Challenge
Problem Statement
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.
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]
Try here before watching the video.
Video Solution
Java Code
class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
if(n <= 2) {
List<Integer> res = new ArrayList<>();
for(int i = 0; i < n; i++) {
res.add(i);
}
return res;
}
List<Integer>[] graph = new List[n];
for(int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for(int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
List<Integer> res = new ArrayList<>();
for(int i = 0; i < n; i++) {
if(graph[i].size() == 1) {
res.add(i);
}
}
while(n > 2) {
n = n - res.size();
List<Integer> currLeaves = new ArrayList<>();
for(int i = 0; i < res.size(); i++) {
int nbr = graph[res.get(i)].get(0);
graph[nbr].remove(res.get(i));
if (graph[nbr].size()==1) {
currLeaves.add(nbr);
}
}
res = currLeaves;
}
return res;
}
}
C++ Code
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if (n <= 2) {
vector<int> res;
for (int i = 0; i < n; i++) {
res.push_back(i);
}
return res;
}
vector<vector<int>> graph(n);
for (const auto& edge : edges) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
vector<int> res;
for (int i = 0; i < n; i++) {
if (graph[i].size() == 1) {
res.push_back(i);
}
}
while (n > 2) {
n -= res.size();
vector<int> currLeaves;
for (int i = 0; i < res.size(); i++) {
int nbr = graph[res[i]][0];
graph[nbr].erase(find(graph[nbr].begin(), graph[nbr].end(), res[i]));
if (graph[nbr].size() == 1) {
currLeaves.push_back(nbr);
}
}
res = currLeaves;
}
return res;
}
};
Python Code
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n <= 2:
return list(range(n))
graph = defaultdict(list)
for edge in edges:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
res = []
for i in range(n):
if len(graph[i]) == 1:
res.append(i)
while n > 2:
n -= len(res)
curr_leaves = []
for node in res:
nbr = graph[node][0]
graph[nbr].remove(node)
if len(graph[nbr]) == 1:
curr_leaves.append(nbr)
res = curr_leaves
return res
Go Code
func findMinHeightTrees(n int, edges [][]int) []int {
if n <= 2 {
res := make([]int, n)
for i := 0; i < n; i++ {
res[i] = i
}
return res
}
graph := make([][]int, n)
for _, edge := range edges {
a, b := edge[0], edge[1]
graph[a] = append(graph[a], b)
graph[b] = append(graph[b], a)
}
res := make([]int, 0)
for i := 0; i < n; i++ {
if len(graph[i]) == 1 {
res = append(res, i)
}
}
for n > 2 {
n -= len(res)
currLeaves := make([]int, 0)
for _, node := range res {
nbr := graph[node][0]
graph[nbr] = removeNode(graph[nbr], node)
if len(graph[nbr]) == 1 {
currLeaves = append(currLeaves, nbr)
}
}
res = currLeaves
}
return res
}
func removeNode(arr []int, val int) []int {
index := -1
for i, v := range arr {
if v == val {
index = i
break
}
}
if index != -1 {
arr = append(arr[:index], arr[index+1:]...)
}
return arr
}
Javascript Code
/**
* @param {number} n
* @param {number[][]} edges
* @return {number[]}
*/
var findMinHeightTrees = function(n, edges) {
if (n <= 2) return Array.from({ length: n }, (_, i) => i);
const graph = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
}
const res = [];
for (let i = 0; i < n; i++) {
if (graph[i].length === 1) res.push(i);
}
while (n > 2) {
n -= res.length;
const currLeaves = [];
for (const node of res) {
const nbr = graph[node][0];
graph[nbr] = graph[nbr].filter(x => x !== node);
if (graph[nbr].length === 1) currLeaves.push(nbr);
}
res.length = 0;
res.push(...currLeaves);
}
return res;
};
Complexity Analysis
Assuming, M represents to number of edges and N to number of vertices
Time Complexity: O(M + N)
Space Complexity: O(N)