Skip to main content

Leetcode 59. Graph Valid Tree. Python (DFS Recursive)

 59. Graph 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

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.


class Solution:
    def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
        if not in n:
            return True
       
        #hm of adjacency list
        hm = { i:[] for i in range(n)}

        for n1, n2 in edges:
            hm[n1].append(n2)
            hm[n2].append(n1)

        vs = set() #visit set

        def dfs(i, prev):
            if i in vs:
                return False

            vs.add(i)
            for j in hm[i]:
                if j == prev:
                    continue
                if not dfs(j, i):
                    return False
            return True
       
        return dfs(0, -1) and n == len(vs)


Explaination :







Comments