1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
graph-valid-tree.py 1.80 KB
一键复制 编辑 原始数据 按行查看 历史
SangHee Kim 提交于 6年前 . small update (#43)
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
import collections
# BFS solution. Same complexity but faster version.
class Solution(object):
# @param {integer} n
# @param {integer[][]} edges
# @return {boolean}
def validTree(self, n, edges):
if len(edges) != n - 1: # Check number of edges.
return False
# init node's neighbors in dict
neighbors = collections.defaultdict(list)
for u, v in edges:
neighbors[u].append(v)
neighbors[v].append(u)
# BFS to check whether the graph is valid tree.
q = collections.deque([0])
visited = set([0])
while q:
curr = q.popleft()
for node in neighbors[curr]:
if node not in visited:
visited.add(node)
q.append(node)
return len(visited) == n
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
# BFS solution.
class Solution2(object):
# @param {integer} n
# @param {integer[][]} edges
# @return {boolean}
def validTree(self, n, edges):
# A structure to track each node's [visited_from, neighbors]
visited_from = [-1] * n
neighbors = collections.defaultdict(list)
for u, v in edges:
neighbors[u].append(v)
neighbors[v].append(u)
# BFS to check whether the graph is valid tree.
q = collections.deque([0])
visited = set([0])
while q:
i = q.popleft()
for node in neighbors[i]:
if node != visited_from[i]:
if node in visited:
return False
else:
visited.add(node)
visited_from[node] = i
q.append(node)
return len(visited) == n
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助