Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #310: Minimum Height Trees

In this guide, we solve Leetcode #310 Minimum Height Trees in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, Graph, Topological Sort

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

Input: n = 4, edges = [[1,0],[1,2],[1,3]] Output: [1] Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.

Python Solution

class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: if n == 1: return [0] g = [[] for _ in range(n)] degree = [0] * n for a, b in edges: g[a].append(b) g[b].append(a) degree[a] += 1 degree[b] += 1 q = deque(i for i in range(n) if degree[i] == 1) ans = [] while q: ans.clear() for _ in range(len(q)): a = q.popleft() ans.append(a) for b in g[a]: degree[b] -= 1 if degree[b] == 1: q.append(b) return ans

Complexity

The time complexity is O(n)O(n)O(n) and the space complexity is O(n)O(n)O(n), where nnn is the number of nodes. The space complexity is O(n)O(n)O(n), where nnn is the number of nodes.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy