Skip to content

Commit 85d2354

Browse files
committed
Sync LeetCode submission Runtime - 1 ms (58.70%), Memory - 18.9 MB (69.09%)
1 parent c802b61 commit 85d2354

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

0261-graph-valid-tree/README.md

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<p>You have a graph of <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given an integer n and a list of <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>
2+
3+
<p>Return <code>true</code> <em>if the edges of the given graph make up a valid tree, and</em> <code>false</code> <em>otherwise</em>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/tree1-graph.jpg" style="width: 222px; height: 302px;" />
8+
<pre>
9+
<strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
10+
<strong>Output:</strong> true
11+
</pre>
12+
13+
<p><strong class="example">Example 2:</strong></p>
14+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/tree2-graph.jpg" style="width: 382px; height: 222px;" />
15+
<pre>
16+
<strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
17+
<strong>Output:</strong> false
18+
</pre>
19+
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= n &lt;= 2000</code></li>
25+
<li><code>0 &lt;= edges.length &lt;= 5000</code></li>
26+
<li><code>edges[i].length == 2</code></li>
27+
<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li>
28+
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
29+
<li>There are no self-loops or repeated edges.</li>
30+
</ul>

0261-graph-valid-tree/solution.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Approach 2: Advanced Graph Theory + Iterative Depth-First Search
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def validTree(self, n: int, edges: List[List[int]]) -> bool:
8+
if len(edges) != (n - 1):
9+
return False
10+
11+
adj_list = [[] for _ in range(n)]
12+
for a, b in edges:
13+
adj_list[a].append(b)
14+
adj_list[b].append(a)
15+
16+
seen = {0}
17+
stack = [0]
18+
19+
while stack:
20+
node = stack.pop()
21+
for neighbor in adj_list[node]:
22+
if neighbor in seen:
23+
continue
24+
seen.add(neighbor)
25+
stack.append(neighbor)
26+
27+
return len(seen) == n
28+

0 commit comments

Comments
 (0)