261. 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.

Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

这里是无向图的遍历,跟有向图不同,需要往堆栈里加入正反两个方向的向量。解法有DFS,BFSh和Union Find。可以先看这篇博客: [LeetCode] Graph Valid Tree 图验证树,里面有三种方法的讲解和源代码。对于union find可以看这篇pdf: https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf。代码如下:
/*public class Solution {
    boolean[] visited;
    
    public boolean validTree(int n, int[][] edges) {
        visited = new boolean[n];
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        for (int i = 0; i < n; i++) {
            lists.add(new ArrayList<Integer>());
        }
        for (int[] pair: edges) {
            lists.get(pair[0]).add(pair[1]);
            lists.get(pair[1]).add(pair[0]);
        }
        if (!helper(lists, 0, -1)) {
            return false;
        }
        for (boolean visit: visited) {
            if (!visit) {
                return false;
            }
        }
        return true;
    }
    
    private boolean helper(List<List<Integer>> lists, int n, int pre) {
        if (visited[n] == true) {
            return false;
        }
        visited[n] = true;
        for (int curr: lists.get(n)) {
            if (curr != pre) {
                if (!helper(lists, curr, n)) {
                    return false;
                }
            }
        }
        return true;
    }
}*/
public class Solution {
    public boolean validTree(int n, int[][] edges) {
        int[] roots = new int[n];
        Arrays.fill(roots, -1);
        for (int[] edge: edges) {
            int x = find(roots, edge[0]);
            int y = find(roots, edge[1]);
            if (x == y) {
                return false;
            }
            roots[x] = y;
        }
        return edges.length == n - 1;
    }
    
    private int find(int[] roots, int n) {
        while(roots[n] != -1) {
            n = roots[n];
        }
        return n;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值