You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
publicclassSolution {
publicbooleanvalidateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
int[] inDegree =newint[n];
for (int i = 0; i < n; i++) {
if (leftChild[i]!=-1) inDegree[leftChild[i]]++;
if (rightChild[i]!=-1) inDegree[rightChild[i]]++;
}
// Determine the root (node with in-degree 0)int root =-1;
for (int i = 0; i < n; i++) {
if (inDegree[i]== 0) {
if (root !=-1) returnfalse; // More than one root root = i;
}
if (inDegree[i]> 1) returnfalse; // Shared children }
if (root ==-1) returnfalse; // No root found// Perform DFS to check connectivityboolean[] visited =newboolean[n];
Stack<Integer> stack =new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
int curr = stack.pop();
if (visited[curr]) returnfalse; // Cycle detected visited[curr]=true;
int left = leftChild[curr], right = rightChild[curr];
if (left !=-1) stack.push(left);
if (right !=-1) stack.push(right);
}
// Check if all nodes are visitedfor (boolean v : visited) {
if (!v) returnfalse;
}
returntrue;
}
}
classSolution:
defvalidateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
in_degree = [0] * n
for i in range(n):
if leftChild[i] !=-1:
in_degree[leftChild[i]] +=1if rightChild[i] !=-1:
in_degree[rightChild[i]] +=1# Determine the root root =-1for i in range(n):
if in_degree[i] ==0:
if root !=-1:
returnFalse# More than one root root = i
if in_degree[i] >1:
returnFalse# Shared childrenif root ==-1:
returnFalse# No root found# Perform DFS to check connectivity visited = [False] * n
defdfs(node: int):
if node ==-1or visited[node]:
return visited[node] =True dfs(leftChild[node])
dfs(rightChild[node])
dfs(root)
# Check if all nodes are visitedreturn all(visited)