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 Macchiato25 天前
Leetcode 3321. Find X-Sum of All K-Long Subarrays II
leetcode·滑动窗口·leetcode hard·leetcode 3321·leetcode周赛419
eggcode3 个月前
旅行商问题变体:欧几里德平面中线段最小连接算法
旅行商问题·图算法
Espresso Macchiato3 个月前
Leetcode 3261. Count Substrings That Satisfy K-Constraint II
滑动窗口·leetcode hard·leetcode周赛411·leetcode 3261·累积数组
Espresso Macchiato3 个月前
Leetcode 3260. Find the Largest Palindrome Divisible by K
leetcode hard·回文·分类讨论·leetcode 3260·leetcode周赛411
xhload3d3 个月前
图扑 HT for Web 轻松构建组态拓扑结构
低代码·3d·智慧城市·数字孪生·可视化·轻量化·组态·拓扑·拓扑图·hightopo·自动布局
Espresso Macchiato4 个月前
Leetcode 3213. Construct String with Minimum Cost
动态规划·leetcode hard·trie树·leetcode 3213·leetcode周赛405
慕羽★4 个月前
一文解决图论中有向图、无向图、非负加权图的单源最短路径问题【超详细】【通用模板程序】【深入分析】【无需基础】【c++】
c++·机器人·图论·路径规划·运动规划·寻路问题·拓扑图
Espresso Macchiato4 个月前
Leetcode 3193. Count the Number of Inversions
leetcode·动态规划·leetcode hard·leetcode 3193·leetcode双周赛133
Espresso Macchiato5 个月前
Leetcode 3187. Peaks in Array
leetcode hard·leetcode周赛402·leetcode 3187·segment tree·分段树