1
var validateBinaryTreeNodes = function (n, leftChild, rightChild) {2
// find in-degree for each node3
const inDeg = new Array(n).fill(0);4
for (let i = 0; i < n; ++i) {5
if (leftChild[i] !== -1) {8
if (rightChild[i] !== -1) {9
++inDeg[rightChild[i]];12
// find the root node and check each node has only one in-degree14
for (let i = 0; i < n; ++i) {17
} else if (inDeg[i] > 1) {21
// if no root node found -> invalid BT22
if (rootNodeId === -1) {25
// BFS to check that each node is visited at least and at most once26
const visited = new Set();27
const queue = [rootNodeId];29
while (queue.length) {30
const nodeId = queue.shift();32
if (visited.has(nodeId)) {37
const leftNode = leftChild[nodeId],38
rightNode = rightChild[nodeId];39
if (leftNode !== -1) {42
if (rightNode !== -1) {43
queue.push(rightNode);46
// checking each node is visited at least once47
return visited.size === n;