← Back to Codes

2026-06-09 16:36:42

Graph Valid Tree in Python and Java | LeetCode #261

Learn how to solve Graph Valid Tree in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Graph Valid Tree in Python and Java

In this tutorial, we will learn LeetCode #261: Graph Valid Tree in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Graph Valid Tree Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use union find because it gives a clean and optimized solution.

Example input:
n = 5, edges = [[0,1],[0,2],[0,3],[3,4]]

Expected result:
Output: true

Explanation:
All nodes are connected and no cycle exists.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
n = 5, edges = [[0,1],[0,2],[0,3],[3,4]]

Approach:
union find

We update variables step by step until we reach:
Output: true

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why union find is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

n = 5, edges = [[0,1],[0,2],[0,3],[3,4]]

We will solve it using union find.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: true

Why?
All nodes are connected and no cycle exists.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: true

Example 1

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

Output:
Output: true

Explanation:
All nodes are connected and no cycle exists.

Example 2

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

Output:
true

Explanation:
All nodes are connected and there is no cycle.

Python Code

Here is the complete Python solution for LeetCode #261.

class GraphValidTreeChecker:
    def valid_tree(self, n, edges):
        if len(edges) != n - 1:
            return False

        graph = [[] for _ in range(n)]
        for a, b in edges:
            graph[a].append(b)
            graph[b].append(a)

        seen = set()

        def dfs(node):
            if node in seen:
                return
            seen.add(node)
            for neighbor in graph[node]:
                dfs(neighbor)

        dfs(0)
        return len(seen) == n


checker = GraphValidTreeChecker()
print(checker.valid_tree(5, [[0, 1], [0, 2], [2, 3], [2, 4]]))  # Output: True
print(checker.valid_tree(4, [[0, 1], [1, 2], [2, 0]]))          # Output: False

Java Code

Here is the complete Java solution for LeetCode #261.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class GraphValidTreeChecker {
    public boolean validTree(int n, int[][] edges) {
        if (edges.length != n - 1) return false;

        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());

        for (int[] edge : edges) {
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
        }

        Set<Integer> seen = new HashSet<>();
        dfs(0, graph, seen);
        return seen.size() == n;
    }

    private void dfs(int node, List<List<Integer>> graph, Set<Integer> seen) {
        if (seen.contains(node)) return;
        seen.add(node);
        for (int neighbor : graph.get(node)) dfs(neighbor, graph, seen);
    }

    public static void main(String[] args) {
        GraphValidTreeChecker checker = new GraphValidTreeChecker();
        System.out.println(checker.validTree(5, new int[][] {{0,1}, {0,2}, {2,3}, {2,4}})); // true
        System.out.println(checker.validTree(4, new int[][] {{0,1}, {1,2}, {2,0}}));        // false
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #261: Graph Valid Tree becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.