Minimum Height Trees
Given n nodes labeled from 0 to n-1 and edges Return a list of all root labels that produce minimum height trees Example: n = 4, edges = [[1,0],[1,2],[1,3]] => [1] Example: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] => [3, 4]
Minimum Height Trees rewards clean traversal structure more than any clever shortcut. Interviewers love it because it reveals your traversal modeling and your edge-case discipline. The trap is revisiting states or missing a base case; your visited/queue logic needs to be tight.
Examples
You write
find_min_height_trees(n: int, edges: List[List[int]])
Example 1
- Input
- n = 4, edges = [[1,0],[1,2],[1,3]]
- returns
- [1]
Example 2
- Input
- n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
- returns
- [3, 4]
Save this for your laptop
The editor and Run need a bigger screen. The link opens Minimum Height Trees ready to code. It is free, and the editor needs no account.
The pattern behind it
BFS & DFS
I reach for it when
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
All 52 BFS & DFS problemsGraphs
I reach for it when
- The input is edges, prerequisites or connections.
- You need cycles, an ordering or connected groups.
Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.
All 32 Graphs problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.