union solution java code


  • 0
    L

    // a tree is acyclic union

        public boolean validTree(int n, int[][] edges) {
                    int[] tree = new int[n];
                  //initialize disjointed sets
                  for(int i = 0; i < n; i++){
                         tree[i] =  i;
                  }
        
        
        for(int[] edge: edges){
            int id1 = find(tree,edge[0]);
            int id2 = find(tree,edge[1]);
            if(id1 == id2) return false;
            else {
                tree[id2] = id1;
            }    
        }
        //check disconnection 
        int id = find(tree,0);
        for(int i = 0 ; i < n; i++){
            if(id != find(tree,i)) return false;
        }
        
        
        
        return true;
    }
    
    private int find(int[] tree,int id){
        while(tree[id] != id){
            tree[id] = tree[tree[id]];
            id = tree[id];
        }
        return id;
    }

  • 0
    L

    //improved version
    //a tree is acyclic union.

      public boolean validTree(int n, int[][] edges) {
        int[] tree = new int[n];
        for(int i = 0; i < n; i++){
            tree[i] =  i;
        }
        
        
        for(int[] edge: edges){
            int id1 = find(tree,edge[0]);
            int id2 = find(tree,edge[1]);
            if(id1 == id2) return false;
            else {
                tree[id2] = id1;
            }    
        }
        
        
        return edges.length == n - 1;
    }
    //return union id
    private int find(int[] tree,int id){
        while(tree[id] != id){
            tree[id] = tree[tree[id]];
            id = tree[id];
        }
        return id;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.