Minimum Height Trees
Try to solve the Minimum Height Trees problem.
We'll cover the following
Statement#
You are given as the number of nodes and a 2D array of edges representing a tree having the following properties:
-
It is an acyclic, undirected graph containing nodes and edges.
-
The nodes are labeled from to .
-
An edge at the index is represented as , which denotes that there is an undirected edge connecting the nodes and .
Your task is to find all possible root nodes that can be used to create trees of minimum height. The height of a tree is the length of the longest path from the root node to any leaf node.
Note: The order of root nodes in the result does not matter.
Constraints
edges.length- Each edge is unique.
Examples#
1 of 3
2 of 3
3 of 3
Understand the problem#
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Minimum Height Trees
What is the output if the following number of nodes and edges are given as input?
n = 4
edges = [[1, 0], [1, 2], [1, 3]]
[0]
[1]
[0, 1]
[1, 3]
Try it yourself#
Implement your solution in the following coding playground.
An optimal solution to this problem runs in O(n) time and takes O(n) space.
Solution: Diameter of Binary Tree
Solution: Minimum Height Trees