forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbky373.java
More file actions
42 lines (36 loc) · 1.06 KB
/
bky373.java
File metadata and controls
42 lines (36 loc) · 1.06 KB
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
/*
time: O(n + m), where n is the number of nodes and m is the number of edges in the graph.
space: O(n + m)
*/
class Solution {
public boolean validTree(int n, int[][] edges) {
if (edges.length != n - 1) {
return false;
}
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
for (int[] edge : edges) {
adjList.get(edge[0])
.add(edge[1]);
adjList.get(edge[1])
.add(edge[0]);
}
Stack<Integer> stack = new Stack<>();
Set<Integer> visited = new HashSet<>();
stack.push(0);
visited.add(0);
while (!stack.isEmpty()) {
int curr = stack.pop();
for (int adj : adjList.get(curr)) {
if (visited.contains(adj)) {
continue;
}
visited.add(adj);
stack.push(adj);
}
}
return visited.size() == n;
}
}