Given n nodes labeled from 0 to n - 1 and 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.
Notice
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.
Example
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Tags
Depth First Search Facebook Zenefits Union FindBreadth First Search Google
Related Problems
Medium Find the Connected Component in the Undirected Graph
“a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
publicclassSolution {publicbooleanvalidTree(int n,int[][] edges) {// initialize adjacency listList<List<Integer>> adjList =newArrayList<List<Integer>>(n);// initialize verticesfor (int i =0; i < n; i++)adjList.add(i,newArrayList<Integer>());// add edges for (int i =0; i <edges.length; i++) {int u = edges[i][0], v = edges[i][1];adjList.get(u).add(v);adjList.get(v).add(u); }boolean[] visited =newboolean[n];// make sure there's no cycleif (hasCycle(adjList,0, visited,-1))returnfalse;// make sure all vertices are connectedfor (int i =0; i < n; i++) {if (!visited[i]) returnfalse; }returntrue; }// check if an undirected graph has cycle started from vertex ubooleanhasCycle2(List<List<Integer>> adjList,int u,boolean[] visited,int parent) {if (visited[u]) {returntrue; } visited[u] =true;for(int v:adjList.get(u)){// skip putting v into recursion again if v == parentif(v != parent &&hasCycle(adjList, v, visited, u)){returntrue; } }returnfalse; }// check if an undirected graph has cycle started from vertex ubooleanhasCycle(List<List<Integer>> adjList,int u,boolean[] visited,int parent) { visited[u] =true;for (int i =0; i <adjList.get(u).size(); i++) {int v =adjList.get(u).get(i);if ((visited[v] && parent != v) || (!visited[v] &&hasCycle(adjList, v, visited, u)))returntrue; }returnfalse; }}
BFS Solution
publicbooleanvalidTree(int n,int[][] edges) {HashMap<Integer,ArrayList<Integer>> map =newHashMap<Integer,ArrayList<Integer>>();for(int i=0; i<n; i++){ArrayList<Integer> list =newArrayList<Integer>();map.put(i, list); }for(int[] edge: edges){map.get(edge[0]).add(edge[1]);map.get(edge[1]).add(edge[0]); }boolean[] visited =newboolean[n];LinkedList<Integer> queue =newLinkedList<Integer>();queue.offer(0);while(!queue.isEmpty()){int top =queue.poll();if(visited[top])returnfalse; visited[top]=true;for(int i:map.get(top)){// only putting new node into the queueif(!visited[i])queue.offer(i); } }// fully connectedfor(boolean b: visited){if(!b)returnfalse; }returntrue;}