-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0261-graph-valid-tree.java
43 lines (32 loc) · 1.13 KB
/
0261-graph-valid-tree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Solution {
private Map<Integer, List<Integer>> adjacencyList = new HashMap<>();
public boolean validTree(int n, int[][] edges) {
if (n == 0 || n == 1) return true;
if (edges.length == 0) return false;
for (var edge : edges) {
var node1 = edge[0];
var node2 = edge[1];
adjacencyList.putIfAbsent(node1, new ArrayList<>());
adjacencyList.putIfAbsent(node2, new ArrayList<>());
adjacencyList.get(node1).add(node2);
adjacencyList.get(node2).add(node1);
}
Set<Integer> visited = new HashSet<>();
return (
depthFirstSearch(edges[0][0], -1, visited) && visited.size() == n
);
}
private boolean depthFirstSearch(
int node,
int previous,
Set<Integer> visited
) {
if (visited.contains(node)) return false;
visited.add(node);
for (var neighbor : adjacencyList.get(node)) {
if (neighbor == previous) continue;
if (!depthFirstSearch(neighbor, node, visited)) return false;
}
return true;
}
}