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.

1。两个edge的father不能xiangtong,否则有环 2。不能有两个parent node Example 1:

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

class Solution {
     public boolean validTree(int n, int[][] edges) {
        if ((edges == null || edges.length == 0) && n > 1) return false;
        UnionFind union = new UnionFind(n);
        for (int i = 0; i < edges.length; i++) {
            int a = edges[i][0];
            int b = edges[i][1];
            if (union.find(a) == union.find(b)) {
                return false;
            }
            union.union(a, b);
        }
        if (union.count > 1) return false;
        return true;
    }

    class UnionFind {
        Map<Integer, Integer> father = new HashMap<>();
        int count;
        public UnionFind(int n) {
            for (int i = 0; i < n; i++) {
                father.put(i, i);
                count = n;
            }
        }

        public int find(int a) {
            int cur = a;
            while(cur != father.get(cur)) {
                cur = father.get(cur);
            }
            int temp = a;
            while(a != father.get(a)) {
                temp = father.get(a);
                father.put(a, cur);
                a = temp;
            }
            return cur;
        }

        public void union(int a, int b) {
            int aFather = father.get(a);
            int bFather = father.get(b);
            if (aFather != bFather) {
                count--;
            }
            father.put(aFather, bFather);
        }
    }

}

results matching ""

    No results matching ""