Skip to content

Commit 3abeffc

Browse files
authored
Update 261. Graph Valid Tree.md
1 parent fb8397d commit 3abeffc

File tree

1 file changed

+34
-25
lines changed

1 file changed

+34
-25
lines changed

docs/Leetcode_Solutions/Python/261. Graph Valid Tree.md

Lines changed: 34 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,71 @@
1-
### 261. Graph Valid Tree
1+
# 261. Graph Valid Tree
22

3+
**<font color=red>难度: Medium</font>**
34

5+
## 刷题内容
46

5-
题目:
6-
<https://leetcode.com/problems/graph-valid-tree/>
7+
> 原题连接
78
9+
* https://leetcode.com/problems/graph-valid-tree/
810

11+
> 内容描述
912
10-
难度 : Medium
13+
```
14+
Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
1115
16+
Example 1:
1217
18+
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
19+
Output: true
20+
Example 2:
1321
14-
思路:
22+
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
23+
Output: false
24+
Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges.
25+
```
1526

16-
graph 为 tree 两个条件:
27+
## 解题方案
1728

18-
- 这个图是connected
19-
- 没有cycle
29+
> 思路 1
30+
******- 时间复杂度: O(V * E)******- 空间复杂度: O(V)******
2031

32+
graph 为 tree 两个条件:
2133

34+
- 这个图完全connected
35+
- 没有cycle
2236

2337
偷懒AC代码,直接在323题,Number of Connected Components in an Undirected Graph上改的AC代码:
2438

2539

2640

27-
```
28-
class Solution(object):
41+
```python
42+
class Solution:
2943
def validTree(self, n, edges):
3044
"""
3145
:type n: int
3246
:type edges: List[List[int]]
3347
:rtype: bool
3448
"""
3549
def find(x):
36-
if uf[x] != x:
37-
uf[x] = find(uf[x])
38-
return uf[x]
50+
while x != uf[x]:
51+
uf[x] = uf[uf[x]]
52+
x = uf[x]
53+
return uf[x]
3954

40-
def union(x,y):
41-
xRoot = find(x)
42-
yRoot = find(y)
43-
uf[xRoot] = yRoot
55+
def union(x, y):
56+
x_root = find(x)
57+
y_root = find(y)
58+
uf[x_root] = y_root
4459

4560
uf = [i for i in range(n)]
4661

4762
for node1, node2 in edges:
48-
# cycle exists
49-
if find(node1) == find(node2):
50-
print 'ha '
63+
if find(node1) == find(node2): # cycle exists
5164
return False
5265
else:
5366
union(node1, node2)
5467

55-
res = set()
56-
for i in range(n):
57-
res.add(find(i))
58-
59-
return len(res) == 1
68+
return len(set(find(i) for i in uf)) == 1 # fully connected
6069
```
6170

6271

0 commit comments

Comments
 (0)