who can tell me what is wrong with this solution?


  • 0
    K
            public boolean validTree(int n, int[][] edges) {
    		int[] roots = new int[n];
    		for (int i=0;i<n;i++) roots[i] = i;
    		for (int[] edge:edges){
    			int root0 = find(roots, edge[0]);
    			int root1 = find(roots, edge[1]);
    			if (root0 == root1) return false;
    			//这里要更新roots的列表
    			roots[edge[0]] = Math.min(root0, root1);
    			roots[edge[1]] = Math.min(root0, root1);
    		}
    		for (int i=0;i<n;i++) if (find(roots, i) != 0)return false; 
    		return true;
    	}
    	
    	private int find(int[] roots, int id){
    		while (roots[id] != id) {
    			id = roots[roots[id]];
    		}
    		return id;
    	}
    

Log in to reply
 

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