Skip to content

Commit 3f71934

Browse files
committed
Solve Graph Valid Tree
1 parent ed0f66f commit 3f71934

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

graph-valid-tree/bky373.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
time: O(n + m), where n is the number of nodes and m is the number of edges in the graph.
3+
space: O(n + m)
4+
*/
5+
class Solution {
6+
7+
public boolean validTree(int n, int[][] edges) {
8+
9+
if (edges.length != n - 1) {
10+
return false;
11+
}
12+
13+
List<List<Integer>> adjList = new ArrayList<>();
14+
for (int i = 0; i < n; i++) {
15+
adjList.add(new ArrayList<>());
16+
}
17+
for (int[] edge : edges) {
18+
adjList.get(edge[0])
19+
.add(edge[1]);
20+
adjList.get(edge[1])
21+
.add(edge[0]);
22+
}
23+
24+
Stack<Integer> stack = new Stack<>();
25+
Set<Integer> visited = new HashSet<>();
26+
stack.push(0);
27+
visited.add(0);
28+
29+
while (!stack.isEmpty()) {
30+
int curr = stack.pop();
31+
for (int adj : adjList.get(curr)) {
32+
if (visited.contains(adj)) {
33+
continue;
34+
}
35+
visited.add(adj);
36+
stack.push(adj);
37+
}
38+
}
39+
40+
return visited.size() == n;
41+
}
42+
}

0 commit comments

Comments
 (0)