1 public class Solution { 2 private int[] parent; 3 public boolean validTree(int n, int[][] edges) { 4 if (n < 2) { 5 return true; 6 } 7 parent = new int[n]; 8 for (int i = 0; i < n; i++) { 9 parent[i] = i;10 }11 12 for (int[] edge : edges) {13 int indexA = findParent(edge[0]);14 int indexB = findParent(edge[1]);15 if (indexA == indexB) {16 return false;17 }18 if (indexA < indexB) {19 parent[indexB] = indexA;20 } else if (indexA > indexB) {21 parent[indexB] = parent[indexA];22 }23 }24 int count = 0;25 for (int i = 0; i < n; i++) {26 if (parent[i] == i) {27 private int findParent(int i) {28 while (i != parent[i]) {29 parent[i] = parent[parent[i]];30 i = parent[i];31 }32 return i;33 }34 }
1. No circle : parent index not equal
2. Only one root.