Problem
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.
Examples
Example 1:
|
|
--- title: MHT Example 1 --- graph LR subgraph MHTs B(1):::mhtRoot B(1) --- A(0) B(1) --- C(2) B(1) --- D(3) end subgraph Other["Other Trees which are not MHT"] A1(0):::mhtRoot B1(1) C1(2) D1(3) A1 --- B1 B1 --- C1 & D1 A2(0) B2(1) C2(2):::mhtRoot D2(3) C2 --- B2 B2 --- A2 & D2 A3(0) B3(1) C3(2) D3(3):::mhtRoot D3 --- B3 B3 --- A3 & C3 end MHTs ~~~ Other classDef mhtRoot fill:#FFD700,stroke:#000,stroke-width:1px,color:#000;
Example 2:
|
|
graph TD A1(0) B1(1) C1(2) D1(3):::mhtRoot E1(4) F1(5) D1 --- A1 & B1 & C1 & E1 E1 --- F1 A2(0) B2(1) C2(2) D2(3) E2(4):::mhtRoot F2(5) E2 --- F2 & D2 D2 --- A2 & B2 & C2 classDef mhtRoot fill:#FFD700,stroke:#000,stroke-width:1px,color:#000;
Solution
Method 1 - Trimming the leaves
What can be root of MHT? It should be center point of graph. Why? Assume simple graph below, where edges represent chains and vertices represents balls tied to chain:
|
|
Now, assume we lift the graph from 1, the height of the tree will be 5:
|
|
If we lift tree from 2, the height will be 4:
|
|
But if we lift from center, the height will be 3:
|
|
Now, we can have 2 cases:
- Case 1 - Odd Diameter - If the diameter of the tree is odd, the center will be a single node, as we see in above example
- Case 2 - Even Diameter - If the diameter of the tree is even, the center will consist of two adjacent nodes.
So, the root of MHT or center of the graph, will consist of at most 2 nodes. To find such nodes, we can do following:
Algorithm
- Build the graph in adjacency list representation
- Identify leaves - leaf node has only 1 node in adjacency list
- Iteratively removing leaf nodes from the graph while updating their neighbors’ degrees until only one or two centroids remain, revealing the minimum height trees.
This implementation is similar to the BFS topological sort. Remove the leaves, update the degrees of inner vertexes. Then remove the new leaves. Doing so level by level until there are 2 or 1 nodes left. What’s left is our answer!
Code
|
|
Complexity
- Time:
O(E + V)
where E and V are number edges and vertices. As initially building graph takes O(E) and then as we add neighbours to queue once, taking O(V + E) - Space:
O(V)
- as we use extra space for queueleaves
anddegree
array.