Skip to content

Commit bec9af0

Browse files
committed
check Array is Level Order traversal of BST
1 parent 37cceff commit bec9af0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use strict';
2+
class NodeDetails {
3+
constructor(data) {
4+
this.data = data;
5+
this.min = -Infinity;
6+
this.max = Infinity;
7+
}
8+
}
9+
10+
function checkArrAsLevelOrderOfBST(arr) {
11+
let queue = [new NodeDetails(arr[0])];
12+
let i = 1;
13+
while (i < arr.length && queue.length != 0) {
14+
let temp = queue.shift();
15+
if (i < arr.length && (arr[i] < temp.data && arr[i] > temp.min)) {
16+
let leftNode = new NodeDetails(arr[i++]);
17+
leftNode.max = temp.data;
18+
leftNode.min = temp.min;
19+
queue.push(leftNode);
20+
}
21+
if (i < arr.length && (arr[i] > temp.data && arr[i] < temp.max)) {
22+
let rightNode = new NodeDetails(arr[i++]);
23+
rightNode.min = temp.data;
24+
rightNode.max = temp.max;
25+
queue.push(rightNode);
26+
}
27+
}
28+
return i == arr.length ? true : false;
29+
}
30+
31+
let arr = [7, 4, 12, 3, 6, 8, 1, 5, 10]
32+
console.log('Array', arr);
33+
console.log('check Array as Level order traversal of BST ?', checkArrAsLevelOrderOfBST(arr))

0 commit comments

Comments
 (0)