AlgoMaster Logo

Minimum Height Trees

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. BFS with Degree Count

Intuition:

The problem of finding the minimum height trees (MHTs) in an undirected graph can be tackled by understanding that the roots of MHTs are the central nodes in the longest path of a tree. For trees, the diameter path has a central point/points which split the path into equal or nearly equal parts, minimizing height from these nodes.

The key is to iteratively remove leaf nodes (nodes with only one connection) layer by layer until only one or two nodes are left. These final nodes represent the root of the minimum height trees.

Steps:

  1. Graph Representation
    • We first create an adjacency list to represent the graph as this will help us easily find neighbors of each node.
  1. Initial Setup:
    • Identify nodes with only one connection (leaves).
    • Use a queue to perform a Breadth-First Search (BFS) starting from these leaves.
  2. Iterative Leaf Removal:
    • Repeatedly remove leaves level by level until one or two nodes remain.
    • For each leaf removed, reduce the degree of its neighbor and if the degree becomes one, it becomes a leaf for the next level.
  3. Identify MHT Roots:
    • When we can't remove any more edges (when the remaining pending nodes are 1 or 2), these nodes are the desired roots of MHTs.

Code: