Graph Valid Tree
Description
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.
Idea
We can simply use BFS but it’s important to know:
- edges are undirected and one edge only appear once. There won’t be [0, 1] and [1,0] at the same time in edges.
- check if the graph has cycle: to build a non circle tree, number of edges == number of nodes - 1
- to be a tree: all the nodes are connected, with no circle
Code
def validTree(self, n, edges):
'''
Important! Check if there is circle in the edges
'''
if len(edges) != n - 1:
return False
graph = self.build_graph(edges)
queue = collections.deque([0])
visited = set([0])
while queue:
current_node = queue.popleft()
for neighbor in graph[current_node]:
if neighbor in visited:
continue
queue.append(neighbor)
visited.add(neighbor)
'''
if we visited all the nodes: True else False
'''
return len(visited) == n
def build_graph(self, edges):
graph = collections.defaultdict(list)
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
return graph