Skip to content

Commit d40a548

Browse files
committed
Add medium problems
1 parent 9683f0d commit d40a548

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
"""
2+
# MINIMUM HEIGHT TREE
3+
4+
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.
5+
6+
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).
7+
8+
Return a list of all MHTs' root labels. You can return the answer in any order.
9+
10+
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
11+
12+
13+
Example 1:
14+
15+
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
16+
Output: [1]
17+
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
18+
Example 2:
19+
20+
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
21+
Output: [3,4]
22+
Example 3:
23+
24+
Input: n = 1, edges = []
25+
Output: [0]
26+
Example 4:
27+
28+
Input: n = 2, edges = [[0,1]]
29+
Output: [0,1]
30+
31+
Constraints:
32+
33+
1 <= n <= 2 * 104
34+
edges.length == n - 1
35+
0 <= ai, bi < n
36+
ai != bi
37+
All the pairs (ai, bi) are distinct.
38+
The given input is guaranteed to be a tree and there will be no repeated edges.
39+
"""
40+
41+
class Solution:
42+
def findMinHeightTrees(self, n: int, edges):
43+
44+
if n <= 2:
45+
return [i for i in range(n)]
46+
47+
adjacencyList = [set() for i in range(n)]
48+
for edge in edges:
49+
start, end = edge
50+
adjacencyList[start].add(end)
51+
adjacencyList[end].add(start)
52+
53+
currentLeaves = []
54+
for vertex, neighbors in enumerate(adjacencyList):
55+
if len(neighbors) == 1:
56+
currentLeaves.append(vertex)
57+
58+
remainingVertices = n
59+
while remainingVertices > 2:
60+
remainingVertices -= len(currentLeaves)
61+
nextLeaves = []
62+
while currentLeaves:
63+
leaf = currentLeaves.pop()
64+
parent = adjacencyList[leaf].pop()
65+
adjacencyList[parent].remove(leaf)
66+
if len(adjacencyList[parent]) == 1:
67+
nextLeaves.append(parent)
68+
69+
currentLeaves = nextLeaves
70+
71+
72+
return currentLeaves
73+

0 commit comments

Comments
 (0)