LeetCode 261. Graph Valid Tree(判断图是否为树)

该博客探讨了LeetCode中的问题261,即如何确定给定的无向边是否构成一棵有效的树。有效树的定义是:一个全连通且无回路的图。文章提到了四种方法来解决这个问题:广度优先搜索、深度优先搜索、按节点大小排序的边排序以及Union-Find算法,并提供了相关的参考资料链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题网址:https://leetcode.com/problems/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.

For example:

Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.

Hint:

  1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
  2. According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

注意,这里的树是普通的树,不是二叉树!

思路:要判断一个图是否为树,首先要知道树的定义。

一棵树必须具备如下特性:

(1)是一个全连通图(所有节点相通)

(2)无回路

其中(2)等价于:(3)图的边数=节点数-1

因此我们可以利用特性(1)(2)或者(1)(3)来判断。


方法一:广度优先搜索。要判断连通性,广度优先搜索法是一个天然的选择,时间复杂度O(n),空间复杂度O(n)。

public class Solution {
    public boolean validTree(int n, int[][] edges) {
        Map<Integer, Set<Integer>> graph = new HashMap<>();
        for(int i=0; i<edges.length; i++) {
            for(int j=0; j<2; j++) {
                Set<Integer> pairs = graph.get(edges[i][j]);
                if (pairs == null) {
                    pairs = new HashSet<>();
                    graph.put(edges[i][j], pairs);
                }
                pairs.add(edges[i][1-j]);
            }
        }
        Set<Integer> visited = new HashSet<>();
        Set<Integer> current = new HashSet<>();
        visited.add(0);
        current.add(0);
        while (!current.isEmpty()) {
            Set<Integer> next = new HashSet<>();
            for(Integer node: current) {
                Set<Integer> pairs = graph.get(node);
                if (pairs == null) continue;
                for(Integer pair: pairs) {
                    if (visited.contains(pair)) return false;
                    next.add(pair);
                    visited.add(pair);
                    graph.get(pair).remove(node);
                }
            }
            current = next;
        }
        return visited.size() == n;
    }
}

方法二:深度优先搜索,搜索目标是遍历全部节点。参考文章:http://buttercola.blogspot.com/2015/08/leetcode-graph-valid-tree.html

public class Solution {
    private boolean[] visited;
    private int visits = 0;
    private boolean isTree = true;
    private void check(int prev, int curr, List<Integer>[] graph) {
        if (!isTree) return;
        if (visited[curr]) {
            isTree = false;
            return;
        }
        visited[curr] = true;
        visits ++;
        for(int next: graph[curr]) {
            if (next == prev) continue;
            check(curr, next, graph);
            if (!isTree) return;
        }
        
    }
    public boolean validTree(int n, int[][] edges) {
        visited = new boolean[n];
        List<Integer>[] graph = new List[n];
        for(int i=0; i<n; i++) graph[i] = new ArrayList<>();
        for(int[] edge: edges) {
            graph[edge[0]].add(edge[1]);
            graph[edge[1]].add(edge[0]);
        }
        check(-1, 0, graph);
        return isTree && visits == n;
    }
}


方法三:按节点大小对边进行排序,原理类似并查集。

public class Solution {
    public boolean validTree(int n, int[][] edges) {
        if (edges.length != n-1) return false;
        Arrays.sort(edges, new Comparator<int[]>() {
           @Override
           public int compare(int[] e1, int[] e2) {
               return e1[0] - e2[0];
           }
        });
        int[] sets = new int[n];
        for(int i=0; i<n; i++) sets[i] = i;
        for(int i=0; i<edges.length; i++) {
            if (sets[edges[i][0]] == sets[edges[i][1]]) return false;
            if (sets[edges[i][0]] == 0) {
                sets[edges[i][1]] = 0;
            } else if (sets[edges[i][1]] == 0) {
                sets[edges[i][0]] = 0;
            } else {
                sets[edges[i][1]] = sets[edges[i][0]];
            }
        }
        return true;
    }
}

方法四:Union-Find

public class Solution {
    public boolean validTree(int n, int[][] edges) {
        if (edges.length != n-1) return false;
        int[] roots = new int[n];
        for(int i=0; i<n; i++) roots[i] = i;
        for(int i=0; i<edges.length; i++) {
            int root1 = root(roots, edges[i][0]);
            int root2 = root(roots, edges[i][1]);
            if (root1 == root2) return false;
            roots[root2] = root1;
        }
        return true;
    }
    private int root(int[] roots, int id) {
        if (id == roots[id]) return id;
        return root(roots, roots[id]);
    }
}

参考文章:

http://blog.csdn.net/dm_vincent/article/details/7655764

http://www.elvisyu.com/graph-valid-tree-union-and-find/

http://blog.csdn.net/pointbreak1/article/details/48796691

http://buttercola.blogspot.com/2015/08/leetcode-graph-valid-tree.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值