|
| 1 | +package problem1361 |
| 2 | + |
| 3 | +/* |
| 4 | +You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], |
| 5 | +return true if and only if all the given nodes form exactly one valid binary tree. |
| 6 | +If node i has no left child then leftChild[i] will equal -1, similarly for the right child. |
| 7 | +Note that the nodes have no values and that we only use the node numbers in this problem. |
| 8 | +*/ |
| 9 | + |
| 10 | +func validateBinaryTreeNodes(n int, leftChild []int, rightChild []int) bool { |
| 11 | + // uf[i] represents the group that is the parent of group i |
| 12 | + var uf = make([]int, n) |
| 13 | + // indegree[i] represents how many nodes lead to node i |
| 14 | + var indegree = make([]int, n) |
| 15 | + |
| 16 | + // Initialize the disjoint set (union find) group |
| 17 | + for i := range uf { |
| 18 | + uf[i] = i |
| 19 | + } |
| 20 | + |
| 21 | + // Loop over the nodes and build the graph |
| 22 | + for i := 0; i < n; i++ { |
| 23 | + // If the is a child node |
| 24 | + if leftChild[i] != -1 { |
| 25 | + // Increment the node's indegree |
| 26 | + indegree[leftChild[i]]++ |
| 27 | + // Update the parent graph |
| 28 | + union(uf, leftChild[i], i) |
| 29 | + } |
| 30 | + |
| 31 | + // Same for right child |
| 32 | + if rightChild[i] != -1 { |
| 33 | + indegree[rightChild[i]]++ |
| 34 | + union(uf, rightChild[i], i) |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // There should be only 1 root (a node with no indegree) |
| 39 | + var foundRoot = false |
| 40 | + for i := range indegree { |
| 41 | + if indegree[i] > 1 { |
| 42 | + return false |
| 43 | + } |
| 44 | + if indegree[i] == 0 { |
| 45 | + if foundRoot { |
| 46 | + return false |
| 47 | + } |
| 48 | + foundRoot = true |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // Find how many different groups there are |
| 53 | + var uniqGroups = map[int]bool{} |
| 54 | + for i := range uf { |
| 55 | + uniqGroups[find(uf, i)] = true |
| 56 | + } |
| 57 | + |
| 58 | + // There should be only one group and one root |
| 59 | + return len(uniqGroups) == 1 && foundRoot |
| 60 | +} |
| 61 | + |
| 62 | +func find(uf []int, x int) int { |
| 63 | + if uf[x] == x { |
| 64 | + // If x is the parent of itself, it is the root of the group |
| 65 | + return uf[x] |
| 66 | + } else { |
| 67 | + // If x is not the parent of itself, we call this function again |
| 68 | + // to find the real parent, and update the map |
| 69 | + uf[x] = find(uf, uf[x]) |
| 70 | + return uf[x] |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +func union(uf []int, x, y int) { |
| 75 | + var rootx, rooty int |
| 76 | + // Finding the roots of x and y |
| 77 | + rootx = find(uf, x) |
| 78 | + rooty = find(uf, y) |
| 79 | + // Setting the root of rootx be rooty effectivly merging the groups |
| 80 | + uf[rootx] = rooty |
| 81 | +} |
0 commit comments