Algo-Sim › Graph Traversal

Graph Valid Tree (undirected cycle)

Medium · Graph Traversal · step through it in Java, Python and C++ on your own input

Do these undirected edges form a tree? DFS that skips the edge back to its parent: any other visited neighbour means a cycle.

Problem

Given n nodes labelled 0..n − 1 and a list of undirected edges, return true if the edges form a valid tree: every node is connected and there is no cycle.

Constraints

Edge cases to test

Follow-up questions

Is there a quick check?
A tree has exactly n − 1 edges and is connected; with n − 1 edges, connectivity alone proves there is no cycle.
What about union-find?
Union each edge; a union of two nodes already joined means a cycle: O(E α(n)).

Solution

Java

public boolean validTree(int n, int[][] edges) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) {
        adj.get(e[0]).add(e[1]);
        adj.get(e[1]).add(e[0]);
    }
    boolean[] visited = new boolean[n];
    if (hasCycle(adj, 0, -1, visited)) return false;
    for (int i = 0; i < n; i++) {
        if (!visited[i]) return false;
    }
    return true;
}

private boolean hasCycle(List<List<Integer>> adj, int node, int parent, boolean[] visited) {
    visited[node] = true;
    for (int next : adj.get(node)) {
        if (next == parent) continue;
        if (visited[next]) return true;
        if (hasCycle(adj, next, node, visited)) return true;
    }
    return false;
}

Python

def valid_tree(n, edges):
    adj = [[] for _ in range(n)]
    for a, b in edges:
        adj[a].append(b)
        adj[b].append(a)
    visited = [False] * n

    def has_cycle(node, parent):
        visited[node] = True
        for nxt in adj[node]:
            if nxt == parent:
                continue
            if visited[nxt]:
                return True
            if has_cycle(nxt, node):
                return True
        return False

    if has_cycle(0, -1):
        return False
    for i in range(n):
        if not visited[i]:
            return False
    return True

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool validTree(int n, vector<vector<int>> &edges) {
        vector<vector<int>> adj = {};
        for (int i = 0; i < n; i++)
            adj.push_back({});
        for (vector<int> &e : edges) {
            adj[e[0]].push_back(e[1]);
            adj[e[1]].push_back(e[0]);
        }
        vector<bool> visited = vector<bool>(n);
        if (hasCycle(adj, 0, -1, visited))
            return false;
        for (int i = 0; i < n; i++) {
            if (!visited[i])
                return false;
        }
        return true;
    }

    bool hasCycle(vector<vector<int>> &adj, int node, int parent, vector<bool> &visited) {
        visited[node] = true;
        for (int next : adj[node]) {
            if (next == parent)
                continue;
            if (visited[next])
                return true;
            if (hasCycle(adj, next, node, visited))
                return true;
        }
        return false;
    }
};

More Graph Traversal problems