Skip to content

Tree DP Rerooting DP

Table of Contents

834. Sum of Distances in Tree

  • LeetCode | 力扣

  • Tags: Dynamic Programming, Tree, Depth First Search, Graph

2581. Count Number of Possible Root Nodes

  • LeetCode | 力扣

  • Tags: Array, Hash Table, Dynamic Programming, Tree, Depth First Search

2858. Minimum Edge Reversals So Every Node Is Reachable

  • LeetCode | 力扣

  • Tags: Dynamic Programming, Depth First Search, Breadth First Search, Graph

310. Minimum Height Trees

  • LeetCode | 力扣

  • Tags: Depth First Search, Breadth First Search, Graph, Topological Sort

from collections import deque
from typing import List


def findMinHeightTrees(n: int, edges: List[List[int]]) -> List[int]:
    if n == 1:
        return [0]

    graph = {i: set() for i in range(n)}
    for u, v in edges:
        graph[u].add(v)
        graph[v].add(u)

    q = deque([i for i in range(n) if len(graph[i]) == 1])
    remaining = n

    while remaining > 2:
        size = len(q)
        remaining -= size

        for _ in range(size):
            cur = q.popleft()
            nei = graph[cur].pop()
            graph[nei].remove(cur)

            if len(graph[nei]) == 1:
                q.append(nei)

    return list(q)


n = 6
edges = [[3, 0], [3, 1], [3, 2], [3, 4], [5, 4]]
print(findMinHeightTrees(n, edges))  # [3, 4]

3241. Time Taken to Mark All Nodes

  • LeetCode | 力扣

  • Tags: Dynamic Programming, Tree, Depth First Search, Graph