LeetCode Solutions
310. Minimum Height Trees
Time: $O(n)$ Space: $O(n)$
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if (n == 1 || edges.empty())
return {0};
vector<int> ans;
unordered_map<int, unordered_set<int>> graph;
for (const vector<int>& e : edges) {
const int u = e[0];
const int v = e[1];
graph[u].insert(v);
graph[v].insert(u);
}
for (const vector<int> & [ label, children ] : graph)
if (children.size() == 1)
ans.push_back(label);
while (n > 2) {
n -= ans.size();
vector<int> nextLeaves;
for (const int leaf : ans) {
const int u = *begin(graph[leaf]);
graph[u].erase(leaf);
if (graph[u].size() == 1)
nextLeaves.push_back(u);
}
ans = nextLeaves;
}
return ans;
}
};
class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
if (n == 0 || edges.length == 0)
return new ArrayList<>(Arrays.asList(0));
List<Integer> ans = new ArrayList<>();
Map<Integer, Set<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; ++i)
graph.put(i, new HashSet<>());
for (int[] e : edges) {
final int u = e[0];
final int v = e[0];
graph.get(u).add(v);
graph.get(v).add(u);
}
for (Map.Entry<Integer, Set<Integer>> entry : graph.entrySet()) {
final int label = entry.getKey();
Set<Integer> children = entry.getValue();
if (children.size() == 1)
ans.add(label);
}
while (n > 2) {
n -= ans.size();
List<Integer> nextLeaves = new ArrayList<>();
for (final int leaf : ans) {
final int u = (int) graph.get(leaf).iterator().next();
graph.get(u).remove(leaf);
if (graph.get(u).size() == 1)
nextLeaves.add(u);
}
ans = nextLeaves;
}
return ans;
}
}
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1 or not edges:
return [0]
ans = []
graph = defaultdict(set)
for u, v in edges:
graph[u].add(v)
graph[v].add(u)
for label, children in graph.items():
if len(children) == 1:
ans.append(label)
while n > 2:
n -= len(ans)
nextLeaves = []
for leaf in ans:
u = next(iter(graph[leaf]))
graph[u].remove(leaf)
if len(graph[u]) == 1:
nextLeaves.append(u)
ans = nextLeaves
return ans