forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidate Binary Tree Nodes.js
47 lines (44 loc) · 1.31 KB
/
Validate Binary Tree Nodes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
var validateBinaryTreeNodes = function(n, leftChild, rightChild) {
// find in-degree for each node
const inDeg = new Array(n).fill(0);
for(let i = 0; i < n; ++i) {
if(leftChild[i] !== -1) {
++inDeg[leftChild[i]];
}
if(rightChild[i] !== -1) {
++inDeg[rightChild[i]];
}
}
// find the root node and check each node has only one in-degree
let rootNodeId = -1;
for(let i = 0; i < n; ++i) {
if(inDeg[i] === 0) {
rootNodeId = i;
} else if(inDeg[i] > 1) {
return false;
}
}
// if no root node found -> invalid BT
if(rootNodeId === -1) {
return false;
}
// BFS to check that each node is visited at least and at most once
const visited = new Set();
const queue = [rootNodeId];
while(queue.length) {
const nodeId = queue.shift();
if(visited.has(nodeId)) {
return false;
}
visited.add(nodeId);
const leftNode = leftChild[nodeId],
rightNode = rightChild[nodeId];
if(leftNode !== -1) {
queue.push(leftNode);
}
if(rightNode !== -1) {
queue.push(rightNode);
}
}
// checking each node is visited at least once
return visited.size === n;};