Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

261. Graph Valid Tree

class Solution:
    def validTree(self, n: int, edges: List[List[int]]) -> bool:
        if len(edges) != n - 1:
            return False

        G = defaultdict(list)
        for a, b in edges:
            G[a].append(b)
            G[b].append(a)

        parent = {0: -1}
        stack = [0]
        while stack:
            node = stack.pop()
            for nei in G[node]:
                if nei == parent[node]:
                    continue
                elif nei in parent:
                    return False
                parent[nei] = node
                stack.append(nei)

        return len(parent) == n