欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Lintcode 3686 · N 叉树的直径【中等 DFS/BFS java答案】

Lintcode 3686 · N 叉树的直径【中等 DFS/BFS java答案】

2025/6/15 11:43:25 来源:https://blog.csdn.net/weixin_37991016/article/details/142993606  浏览:    关键词:Lintcode 3686 · N 叉树的直径【中等 DFS/BFS java答案】

题目

在这里插入图片描述
在这里插入图片描述
题目链接:https://www.lintcode.com/problem/3686/

思路

1.利用map创建图
2.找到直径的其中一个端点last,通过bfs可以实现
3.从last出发,再次bfs,有多少层,直径就是多少

Java代码

/*** Definition for Undirected graph.* class UndirectedGraphNode {*     int label;*     List<UndirectedGraphNode> neighbors;*     UndirectedGraphNode(int x) {*         label = x;*         neighbors = new ArrayList<UndirectedGraphNode>();*     }* }*/public class Solution {/*** @param root: the root of the tree* @return: Maximum diameter of the N-ary Tree*/public int diameter(UndirectedGraphNode root) {if(root ==null) return 0;Map<UndirectedGraphNode, Set<UndirectedGraphNode>> graph = new HashMap<>();buildGraph(root, graph);//宽度右边遍历2次,第一次最后遍历到的节点last,// last一定是直径的一个端点之一// 那么从last出发,再次宽度优先遍历,有几层,直径就是几Set<UndirectedGraphNode> visited = new HashSet<>();UndirectedGraphNode last = null;Queue<UndirectedGraphNode> q = new LinkedList<>();q.add(root);visited.add(root);while (!q.isEmpty()){int size = q.size();for (int i = 0; i <size ; i++) {UndirectedGraphNode pop = q.poll();Set<UndirectedGraphNode> nexts = graph.get(pop);for (UndirectedGraphNode next : nexts) {if(!visited.contains(next)){q.add(next);last = next;visited.add(next);}}}}//从last出发再次BFSint ans =0;visited.clear();q.add(last);visited.add(last);while (!q.isEmpty()){ans++;int size = q.size();for (int i = 0; i <size ; i++) {UndirectedGraphNode pop = q.poll();Set<UndirectedGraphNode> nexts = graph.get(pop);for (UndirectedGraphNode next : nexts) {if(!visited.contains(next)){q.add(next);visited.add(next);}}}}return ans-1;}public void buildGraph(UndirectedGraphNode cur, Map<UndirectedGraphNode, Set<UndirectedGraphNode>> g) {//建立图if (cur == null) return;if (!g.containsKey(cur)) {g.put(cur, new HashSet<>());}for (UndirectedGraphNode next : cur.neighbors) {if (!g.containsKey(next)) {g.put(next, new HashSet<>());}g.get(cur).add(next);g.get(next).add(cur);buildGraph(next, g);}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词