Browse curriculum

Graph Valid Tree (LeetCode 261)

Graph Valid Tree (LeetCode 261): determine if a set of edges forms a valid tree.

Examples

Input:n = 5, edges = [[0,1], [0,2], [0,3], [1,4]]
Output:true
Explain:

No cycles, fully connected.

Input:n = 5, edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output:false
Explain:

Cycle exists: 1-2-3-1.

Problem Understanding

A Tree is a special type of Graph that satisfies two conditions:

  1. Fully Connected: You can reach any node from any other node.
  2. Acyclic: It contains no cycles.

Alternatively: A graph with N nodes is a tree if it is fully connected and has exactly N - 1 edges.

Algorithm Strategy (DFS)

We can use DFS to check for cycles and connectivity.

  1. Build Graph: Create adjacency list.
  2. DFS from Node 0: Keep track of visited set to detect cycles.
    • Since the graph is undirected, A-B means B is a neighbor of A. We must not count the immediate parent as a cycle.
    • Pass parent to the DFS call: dfs(node, parent).
    • If neighbor != parent and neighbor is visited -> Cycle Detected! Return false.
  3. Check Connectivity: After DFS, visited.size() must equal n. If not, the graph is disconnected.

Visualization

GREEN = EDGES DFS WALKED · RED = THE EDGE THAT CLOSES A CYCLE

BUILD LIST

Edges

4 (n − 1 = 4)

Visited

0 / 5

Valid tree

:

call stack

No dfs running

 

Build the adjacency list: 5 lists, each of the 4 edges added to both ends

Next

Call dfs(0, -1): start at node 0, which has no parent

Free preview: the first 7 of 21 steps

edges

n

5

DFS from node 0 carries the node it came from. The edge back to that parent is skipped; any other edge that leads to a node already visited closes a cycle, and it turns red. Green edges are the ones DFS walked down. If DFS finishes without a cycle, the last check looks for a node it never reached: try the Two pieces preset.

Dry Run

Input: n = 5, edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Adjacency list: 0:[1], 1:[0,2,3,4], 2:[1,3], 3:[2,1], 4:[1]

Step Call Visited Action
1 dfs(0, -1) {0} Mark 0. Neighbour 1: call dfs(1, 0).
2 dfs(1, 0) {0, 1} Mark 1. Neighbour 0 is the parent: skip. Neighbour 2: call dfs(2, 1).
3 dfs(2, 1) {0, 1, 2} Mark 2. Neighbour 1 is the parent: skip. Neighbour 3: call dfs(3, 2).
4 dfs(3, 2) {0, 1, 2, 3} Mark 3. Neighbour 2 is the parent: skip. Neighbour 1: call dfs(1, 3).
5 dfs(1, 3) {0, 1, 2, 3} 1 is already visited. The edge 3-1 closes the cycle 1-2-3. Return false.
6 Unwind - dfs(3, 2), dfs(2, 1), dfs(1, 0) and dfs(0, -1) each return false. The answer is false.

Edge Cases & Common Mistakes

  • Disconnected Graph: No cycle, but not a tree (forest). Must check visited.size() == n.
  • Single Node: LeetCode guarantees n ≥ 1. One node with no edges is a valid tree: there is no cycle, and DFS from node 0 reaches everything.
  • Self-Loops and Repeated Edges: LeetCode rules both out, and the parent check relies on it: a second copy of the edge back to the parent would be skipped too, so that two-edge cycle would go unnoticed.

Solution

DFS from node 0 with the parent passed down, then a check that every node was visited. Reaching a visited node through any edge except the one back to the parent means a cycle.

Note: LeetCode 261 is a Premium problem.

Graph Valid Tree Code
1var validTree = function(n, edges) {
2 const graph = Array.from({ length: n }, () => []);
3 for (const [a, b] of edges) {
4 graph[a].push(b);
5 graph[b].push(a);
6 }
7
8 const visited = new Array(n).fill(false);
9
10 function dfs(node, parent) {
11 if (visited[node]) {
12 return false;
13 }
14 visited[node] = true;
15 for (const neighbor of graph[node]) {
16 if (neighbor === parent) {
17 continue;
18 }
19 if (!dfs(neighbor, node)) {
20 return false;
21 }
22 }
23 return true;
24 }
25
26 if (!dfs(0, -1)) {
27 return false;
28 }
29 for (let node = 0; node < n; node++) {
30 if (!visited[node]) {
31 return false;
32 }
33 }
34 return true;
35};

Graph Valid Tree in Python, Java, C++, TypeScript and C

Graph Valid Tree in Python
class Solution:
    def validTree(self, n: int, edges: List[List[int]]) -> bool:
        graph = [[] for _ in range(n)]
        for a, b in edges:
            graph[a].append(b)
            graph[b].append(a)

        visited = [False] * n

        def dfs(node, parent):
            if visited[node]:
                return False
            visited[node] = True
            for neighbor in graph[node]:
                if neighbor == parent:
                    continue
                if not dfs(neighbor, node):
                    return False
            return True

        if not dfs(0, -1):
            return False
        for node in range(n):
            if not visited[node]:
                return False
        return True
Graph Valid Tree in Java
class Solution {
    public boolean validTree(int n, int[][] edges) {
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            graph.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            int a = edge[0], b = edge[1];
            graph.get(a).add(b);
            graph.get(b).add(a);
        }

        boolean[] visited = new boolean[n];
        if (!dfs(0, -1, graph, visited)) {
            return false;
        }
        for (int node = 0; node < n; node++) {
            if (!visited[node]) {
                return false;
            }
        }
        return true;
    }

    private boolean dfs(int node, int parent, List<List<Integer>> graph, boolean[] visited) {
        if (visited[node]) {
            return false;
        }
        visited[node] = true;
        for (int neighbor : graph.get(node)) {
            if (neighbor == parent) {
                continue;
            }
            if (!dfs(neighbor, node, graph, visited)) {
                return false;
            }
        }
        return true;
    }
}
Graph Valid Tree in C++
class Solution {
public:
    bool validTree(int n, vector<vector<int>>& edges) {
        vector<vector<int>> graph(n);
        for (auto& edge : edges) {
            int a = edge[0], b = edge[1];
            graph[a].push_back(b);
            graph[b].push_back(a);
        }

        vector<bool> visited(n, false);
        if (!dfs(0, -1, graph, visited)) {
            return false;
        }
        for (int node = 0; node < n; node++) {
            if (!visited[node]) {
                return false;
            }
        }
        return true;
    }

private:
    bool dfs(int node, int parent, vector<vector<int>>& graph, vector<bool>& visited) {
        if (visited[node]) {
            return false;
        }
        visited[node] = true;
        for (int neighbor : graph[node]) {
            if (neighbor == parent) {
                continue;
            }
            if (!dfs(neighbor, node, graph, visited)) {
                return false;
            }
        }
        return true;
    }
};
Graph Valid Tree in TypeScript
function validTree(n: number, edges: number[][]): boolean {
    const graph: number[][] = Array.from({ length: n }, () => []);
    for (const [a, b] of edges) {
        graph[a].push(b);
        graph[b].push(a);
    }

    const visited: boolean[] = new Array(n).fill(false);

    function dfs(node: number, parent: number): boolean {
        if (visited[node]) {
            return false;
        }
        visited[node] = true;
        for (const neighbor of graph[node]) {
            if (neighbor === parent) {
                continue;
            }
            if (!dfs(neighbor, node)) {
                return false;
            }
        }
        return true;
    }

    if (!dfs(0, -1)) {
        return false;
    }
    for (let node = 0; node < n; node++) {
        if (!visited[node]) {
            return false;
        }
    }
    return true;
}
Graph Valid Tree in C
static bool dfs(int node, int parent, int** graph, int* graphSize, bool* visited) {
    if (visited[node]) {
        return false;
    }
    visited[node] = true;
    for (int i = 0; i < graphSize[node]; i++) {
        int neighbor = graph[node][i];
        if (neighbor == parent) {
            continue;
        }
        if (!dfs(neighbor, node, graph, graphSize, visited)) {
            return false;
        }
    }
    return true;
}

bool validTree(int n, int** edges, int edgesSize, int* edgesColSize) {
    int** graph = malloc(n * sizeof(int*));
    int* graphSize = calloc(n, sizeof(int));
    int* degree = calloc(n, sizeof(int));
    for (int i = 0; i < edgesSize; i++) {
        degree[edges[i][0]]++;
        degree[edges[i][1]]++;
    }
    for (int i = 0; i < n; i++) {
        graph[i] = malloc((degree[i] + 1) * sizeof(int));
    }
    for (int i = 0; i < edgesSize; i++) {
        int a = edges[i][0], b = edges[i][1];
        graph[a][graphSize[a]++] = b;
        graph[b][graphSize[b]++] = a;
    }

    bool* visited = calloc(n, sizeof(bool));
    bool valid = dfs(0, -1, graph, graphSize, visited);
    for (int node = 0; valid && node < n; node++) {
        if (!visited[node]) {
            valid = false;
        }
    }

    for (int i = 0; i < n; i++) {
        free(graph[i]);
    }
    free(graph);
    free(graphSize);
    free(degree);
    free(visited);
    return valid;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Build the adjacency list

    Add each undirected edge to both of its nodes' lists.

  2. Look for a cycle

    Run DFS from node 0 with parent -1. Reaching a visited node through any edge except the parent's means a cycle: return false.

  3. Check connectivity

    If any node is still unvisited, return false; otherwise return true.

Frequently asked questions

What makes a graph a valid tree?

It is connected and has no cycles. Equivalently, it is connected and has exactly n - 1 edges.


Why pass the parent into DFS?

In an undirected graph every edge is in both nodes' lists, so a node always sees the node it came from as a neighbour. Skipping that one edge stops it being mistaken for a cycle; any other visited neighbour really does close one.


Why check that every node was visited?

A graph can have no cycle and still be in several pieces. DFS from node 0 only reaches its own piece, so any node left unvisited means the graph is not connected.

New to the technique behind this problem? Watch it run step by step:

Depth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description