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

原题网址: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> graph = new HashMap<>();
        for(int i=0; i 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 visited = new HashSet<>();
        Set current = new HashSet<>();
        visited.add(0);
        current.add(0);
        while (!current.isEmpty()) {
            Set next = new HashSet<>();
            for(Integer node: current) {
                Set 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[] 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[] graph = new List[n];
        for(int i=0; i();
        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() {
           @Override
           public int compare(int[] e1, int[] e2) {
               return e1[0] - e2[0];
           }
        });
        int[] sets = new int[n];
        for(int i=0; i

方法四: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

参考文章:

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

你可能感兴趣的:(图,树,连通性,广度优先搜索,深度优先搜索,并查集)