Skip to content

Commit 2c1e8b5

Browse files
committed
Added graphValidTree solution
1 parent a24465c commit 2c1e8b5

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

graph-valid-tree/nhistory.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution {
2+
/**
3+
* @param {number} n
4+
* @param {number[][]} edges
5+
* @returns {boolean}
6+
*/
7+
validTree(n, edges) {
8+
// A valid tree must have exactly n - 1 edges
9+
if (edges.length !== n - 1) {
10+
return false;
11+
}
12+
13+
// Initialize the adjacency list
14+
let graph = [];
15+
for (let i = 0; i < n; i++) {
16+
graph.push([]);
17+
}
18+
19+
// Populate the adjacency list with edges
20+
for (let [node, neighbor] of edges) {
21+
graph[node].push(neighbor);
22+
graph[neighbor].push(node);
23+
}
24+
25+
let visited = new Set();
26+
27+
// Depth-First Search (DFS) to explore the graph
28+
function dfs(node) {
29+
visited.add(node);
30+
for (let neighbor of graph[node]) {
31+
if (!visited.has(neighbor)) {
32+
dfs(neighbor);
33+
}
34+
}
35+
}
36+
37+
// Start DFS from node 0
38+
dfs(0);
39+
40+
// Check if all nodes were visited
41+
return visited.size === n;
42+
}
43+
}
44+
45+
// TC: O(n)
46+
// SC: O(n)

0 commit comments

Comments
 (0)