Valid Tree
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.
Example 1:
Input:
n = 5
edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output:
true
Example 2:
Input:
n = 5
edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output:
false
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.
Constraints:
1 <= n <= 100
0 <= edges.length <= n * (n - 1) / 2
Solution
To check if this graph is a tree, there are 2 principles.
- There cannot be a loop.
- All the nodes are connected.
DFS can easily check the principles above. All we need to do is to record whether we have visited a node. If we reach a node that has been visited before and the node is not parent node the current node, there is a loop.
After one DFS, if there are still nodes that has not been visited, not all nodes are connected.
Code
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
vis_flag = [False] * n
tree_map = {i: [] for i in range(n)}
for edge in edges:
tree_map[edge[0]].append(edge[1])
tree_map[edge[1]].append(edge[0])
def dfs(father, curr):
vis_flag[curr] = True
for nxt in tree_map[curr]:
if nxt == father:
continue
if vis_flag[nxt]:
return False
if not dfs(curr, nxt):
return False
return True
if not dfs(None, 0):
return False
for flag in vis_flag:
if not flag:
return False
return True