Givennnodes labeled from0ton-1and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
you can assume that no duplicate edges will appear in edges.
Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges.
make sure there's no cycle:记录parent,对于visited过的节点,有环的话会有neighbor的值不等于其parent,因为有环又会dfs回来,相反的没有环的话,visited的neighbor都会等于其parent,因为这里是无向图。但是这里假设没有自己点成环的情况,如[1,1]
make sure all vertices are connected: 利用visited数组,对于树不能有不连接的部分
classSolution {publicbooleanvalidTree(int n,int[][] edges) {if (n ==0) {returnfalse; }/** if (edges.length != n - 1) { return false; } **/Map<Integer,Set<Integer>> graph =initializeGraph(n, edges);boolean[] visited =newboolean[n];// make sure there's no cycleif (hasCycle(graph,0, visited,-1)) {returnfalse; }// make sure all vertices are connectedfor (int i =0; i < n; i++) {if (!visited[i]) {returnfalse; } }returntrue; }privatebooleanhasCycle(Map<Integer,Set<Integer>> graph,int node,boolean[] visited,int parent) { visited[node] =true;for (Integer neighbor :graph.get(node)) {// If an adjacent is not visited, then recur for that adjacentif (!visited[neighbor]) {if (hasCycle(graph, neighbor, visited, node)) {returntrue; } } elseif (neighbor != parent) {// If an adjacent is visited and not parent of current vertex, then there is a cycle.returntrue; } }returnfalse; }privateMap<Integer,Set<Integer>> initializeGraph(int n,int[][] edges) {Map<Integer,Set<Integer>> graph =newHashMap<>();for (int i =0; i < n; i++) {graph.put(i,newHashSet<Integer>()); }for (int i =0; i <edges.length; i++) {int u = edges[i][0];int v = edges[i][1];graph.get(u).add(v);graph.get(v).add(u); }return graph; }}