Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 310 Minimum Height Trees - Implementation

Topological peeling

Start with all degree-11 nodes (leaves) in a queue. Remove them, decrement neighbors' degrees, add new leaves to queue. Repeat until 2\leq 2 nodes remain. These are the minimum height tree roots. Why 2\leq 2? The centroid of a tree is either one node or an edge. If it's an edge, both endpoints are valid roots. Time: O(n)O(n). Each node is added to the queue exactly once. Space: O(n)O(n) for the degree array and queue.

Time complexity: O(n)O(n).

Space complexity: O(n)O(n).