返回介绍

solution / 0300-0399 / 0310.Minimum Height Trees / README_EN

发布于 2024-06-17 01:04:02 字数 7405 浏览 0 评论 0 收藏 0

310. Minimum Height Trees

中文文档

Description

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.

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs).

Return _a list of all MHTs' root labels_. You can return the answer in any order.

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

 

Example 1:

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.

Example 2:

Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]

 

Constraints:

  • 1 <= n <= 2 * 104
  • edges.length == n - 1
  • 0 <= ai, bi < n
  • ai != bi
  • All the pairs (ai, bi) are distinct.
  • The given input is guaranteed to be a tree and there will be no repeated edges.

Solutions

Solution 1: Topological Sorting

If the tree only has one node, then this node is the root of the minimum height tree. We can directly return this node.

If the tree has multiple nodes, there must be leaf nodes. A leaf node is a node that only has one adjacent node. We can use topological sorting to peel off the leaf nodes from the outside to the inside. When we reach the last layer, the remaining nodes are the root nodes of the minimum height tree.

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

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
class Solution {
  public List<Integer> findMinHeightTrees(int n, int[][] edges) {
    if (n == 1) {
      return List.of(0);
    }
    List<Integer>[] g = new List[n];
    Arrays.setAll(g, k -> new ArrayList<>());
    int[] degree = new int[n];
    for (int[] e : edges) {
      int a = e[0], b = e[1];
      g[a].add(b);
      g[b].add(a);
      ++degree[a];
      ++degree[b];
    }
    Deque<Integer> q = new ArrayDeque<>();
    for (int i = 0; i < n; ++i) {
      if (degree[i] == 1) {
        q.offer(i);
      }
    }
    List<Integer> ans = new ArrayList<>();
    while (!q.isEmpty()) {
      ans.clear();
      for (int i = q.size(); i > 0; --i) {
        int a = q.poll();
        ans.add(a);
        for (int b : g[a]) {
          if (--degree[b] == 1) {
            q.offer(b);
          }
        }
      }
    }
    return ans;
  }
}
class Solution {
public:
  vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
    if (n == 1) {
      return {0};
    }
    vector<vector<int>> g(n);
    vector<int> degree(n);
    for (auto& e : edges) {
      int a = e[0], b = e[1];
      g[a].push_back(b);
      g[b].push_back(a);
      ++degree[a];
      ++degree[b];
    }
    queue<int> q;
    for (int i = 0; i < n; ++i) {
      if (degree[i] == 1) {
        q.push(i);
      }
    }
    vector<int> ans;
    while (!q.empty()) {
      ans.clear();
      for (int i = q.size(); i > 0; --i) {
        int a = q.front();
        q.pop();
        ans.push_back(a);
        for (int b : g[a]) {
          if (--degree[b] == 1) {
            q.push(b);
          }
        }
      }
    }
    return ans;
  }
};
func findMinHeightTrees(n int, edges [][]int) (ans []int) {
  if n == 1 {
    return []int{0}
  }
  g := make([][]int, n)
  degree := make([]int, n)
  for _, e := range edges {
    a, b := e[0], e[1]
    g[a] = append(g[a], b)
    g[b] = append(g[b], a)
    degree[a]++
    degree[b]++
  }
  q := []int{}
  for i, d := range degree {
    if d == 1 {
      q = append(q, i)
    }
  }
  for len(q) > 0 {
    ans = []int{}
    for i := len(q); i > 0; i-- {
      a := q[0]
      q = q[1:]
      ans = append(ans, a)
      for _, b := range g[a] {
        degree[b]--
        if degree[b] == 1 {
          q = append(q, b)
        }
      }
    }
  }
  return
}
function findMinHeightTrees(n: number, edges: number[][]): number[] {
  if (n === 1) {
    return [0];
  }
  const g: number[][] = Array.from({ length: n }, () => []);
  const degree: number[] = Array(n).fill(0);
  for (const [a, b] of edges) {
    g[a].push(b);
    g[b].push(a);
    ++degree[a];
    ++degree[b];
  }
  const q: number[] = [];
  for (let i = 0; i < n; ++i) {
    if (degree[i] === 1) {
      q.push(i);
    }
  }
  const ans: number[] = [];
  while (q.length > 0) {
    ans.length = 0;
    const t: number[] = [];
    for (const a of q) {
      ans.push(a);
      for (const b of g[a]) {
        if (--degree[b] === 1) {
          t.push(b);
        }
      }
    }
    q.splice(0, q.length, ...t);
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文