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.
Note: you can assume that no duplicate edges will appear inedges. Since all edges are undirected,[0, 1]is the same as[1, 0]and thus will not appear together inedges.
classSolution {publicbooleanvalidTree(int n,int[][] edges) {List<Set<Integer>> adjList =newArrayList<>();for (int i =0; i < n; i++) {adjList.add(newHashSet<>()); }for (int[] edge : edges) {adjList.get(edge[0]).add(edge[1]);adjList.get(edge[1]).add(edge[0]); }boolean[] visited =newboolean[n];// Check if graph has cycleif (hasCycle(0, visited, adjList,-1)) {returnfalse; }// Check if graph is connectedfor (int i =0; i < n; i++) {if (!visited[i]) {returnfalse; } }returntrue; }publicbooleanhasCycle(int node,boolean[] visited,List<Set<Integer>> adjList,int parent) { visited[node] =true;for (int nextNode :adjList.get(node)) {// (1) If nextNode is visited but it is not the parent of the curNode, then there is cycle// (2) If nextNode is not visited but we still find the cycle later on, return true;if ((visited[nextNode] && parent != nextNode) || (!visited[nextNode] &&hasCycle(nextNode, visited, adjList, node))) {returntrue; } }returnfalse; }}