The Minimum Height Trees problem is a unique graph challenge. You are given a tree (an undirected graph with no cycles) and you need to find all nodes that, when chosen as the root, produce a tree with the minimum possible height. The height of a tree is the maximum distance from the root to any leaf. Finding these "central" nodes is key to balancing the tree structure.
This question is a favorite at companies like Microsoft, PhonePe, and Adobe because it tests a candidate's ability to think about graph properties beyond basic traversals. The Minimum Height Trees interview question evaluates whether you can identify the "Centroid" of a tree. It requires a clever application of Topological Sort principles to an undirected graph, shifting the perspective from "top-down" to "outside-in."
The algorithmic pattern used is a variant of Topological Sort (similar to Kahn's algorithm) applied to an undirected tree. The idea is to iteratively remove all leaf nodes (nodes with degree 1) until only one or two nodes remain. These remaining nodes are the centroids of the tree and will result in the Minimum Height Trees. This "Graph, BFS, Topological Sort interview pattern" is efficient with a time complexity of .
Consider a tree: .
A common error in the Minimum Height Trees coding problem is trying to calculate the height of the tree for every possible root using BFS/DFS. This results in an solution, which is too slow for large graphs (). Another mistake is not correctly managing the degrees of the nodes as leaves are removed, or failing to handle the base case of 1 or 2 nodes correctly.
Master the "iterative leaf removal" technique. It's a powerful way to find the center of any tree structure. Remember that a tree can have at most two centroids. This "Graph Centroid pattern" is very useful for problems involving minimizing distances or balancing hierarchical data.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Eventual Safe States | Medium | Solve | |
| Course Schedule IV | Medium | Solve | |
| All Ancestors of a Node in a Directed Acyclic Graph | Medium | Solve | |
| Course Schedule II | Medium | Solve | |
| Course Schedule | Medium | Solve |