Graph 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.Example
Input:n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: trueInput:n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: falseCode1
class Solution {
public boolean validTree(int n, int[][] edges) {
if (n == 0) {
return false;
}
/**
if (edges.length != n - 1) {
return false;
}
**/
Map<Integer, Set<Integer>> graph = initializeGraph(n, edges);
boolean[] visited = new boolean[n];
// make sure there's no cycle
if (hasCycle(graph, 0, visited, -1)) {
return false;
}
// make sure all vertices are connected
for (int i = 0; i < n; i++) {
if (!visited[i]) {
return false;
}
}
return true;
}
private boolean hasCycle(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 adjacent
if (!visited[neighbor]) {
if (hasCycle(graph, neighbor, visited, node)) {
return true;
}
} else if (neighbor != parent) {
// If an adjacent is visited and not parent of current vertex, then there is a cycle.
return true;
}
}
return false;
}
private Map<Integer, Set<Integer>> initializeGraph(int n, int[][] edges) {
Map<Integer, Set<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
graph.put(i, new HashSet<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;
}
}Code2
Last updated