Leetcode 3203. Find Minimum Diameter After Merging Two Trees

  • [Leetcode 3203. Find Minimum Diameter After Merging Two Trees](#Leetcode 3203. Find Minimum Diameter After Merging Two Trees)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题的话算是一个拓扑树的题目?总之就是从树的叶子节点不断向上遍历,不断地删除已访问的叶子节点,并加入更新之后的新的叶子节点,这样我们就能得到树的最大深度,然后在遍历过程中我们考察其任意节点上的当前深度和已有深度的和的最大值,即为经过该节点的最大路径长度,遍历整张图,我们即刻获得整个树的深度和diameter。然后,我们要连接两个图的话,能够获得的最大路径长度就是两个图的深度之和加一。

由此,我们即可完成这道题目了。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def minimumDiameterAfterMerge(self, edges1: List[List[int]], edges2: List[List[int]]) -> int:
        
        def dfs(edges):
            if edges == []:
                return 0, 0
            diameter = 0
            graph = defaultdict(list)
            deg = defaultdict(int)
            for u, v in edges:
                graph[u].append(v)
                graph[v].append(u)
                deg[u] += 1
                deg[v] += 1
            seen = set()
            leafs = [u for u in deg if deg[u] == 1]
            depth = defaultdict(int)
            while leafs != []:
                u = leafs.pop(0)
                if u in seen:
                    continue
                seen.add(u)
                for v in graph[u]:
                    if v in seen:
                        continue
                    diameter = max(diameter, depth[v] + depth[u] + 1)
                    depth[v] = max(depth[v], depth[u]+1)
                    deg[v] -= 1
                    if deg[v] == 1:
                        leafs.append(v)
            return max(depth.values()), diameter
        
        depth1, diameter1 = dfs(edges1)
        depth2, diameter2 = dfs(edges2)
        return max(depth1 + depth2 + 1, diameter1, diameter2)

提交代码评测得到:耗时3216ms,占用内存93.4MB。

相关推荐
Espresso Macchiato7 天前
Leetcode 3389. Minimum Operations to Make Character Frequencies Equal
动态规划·leetcode hard·分类讨论·leetcode 3389·leetcode周赛428
chencjiajy13 天前
图社区发现算法--Leiden算法
算法·图算法·社区发现算法
Espresso Macchiato21 天前
Leetcode 3373. Maximize the Number of Target Nodes After Connecting Trees II
动态规划·leetcode hard·leetcode 3373·leetcode周赛426·树的遍历
chencjiajy1 个月前
基于的图的异常检测算法OddBall
异常检测·图算法·oddball
Espresso Macchiato1 个月前
Leetcode 3352. Count K-Reducible Numbers Less Than N
动态规划·二进制·leetcode hard·leetcode 3352·leetcode周赛423
Espresso Macchiato2 个月前
Leetcode 3321. Find X-Sum of All K-Long Subarrays II
leetcode·滑动窗口·leetcode hard·leetcode 3321·leetcode周赛419
eggcode4 个月前
旅行商问题变体:欧几里德平面中线段最小连接算法
旅行商问题·图算法
Espresso Macchiato4 个月前
Leetcode 3261. Count Substrings That Satisfy K-Constraint II
滑动窗口·leetcode hard·leetcode周赛411·leetcode 3261·累积数组
Espresso Macchiato4 个月前
Leetcode 3260. Find the Largest Palindrome Divisible by K
leetcode hard·回文·分类讨论·leetcode 3260·leetcode周赛411
xhload3d5 个月前
图扑 HT for Web 轻松构建组态拓扑结构
低代码·3d·智慧城市·数字孪生·可视化·轻量化·组态·拓扑·拓扑图·hightopo·自动布局