Skip to content

Commit f09d0d0

Browse files
committed
construct sorted Arr to balanced BST
1 parent bd31273 commit f09d0d0

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'use strict';
2+
class Node {
3+
constructor(data) {
4+
this.data = data;
5+
this.leftNode = this.rightNode = null;
6+
}
7+
}
8+
9+
function constructBBST(arr, startIndex, endIndex) {
10+
if (startIndex > endIndex) return null;
11+
if (startIndex == endIndex) return new Node(arr[startIndex]);
12+
let midIndex = parseInt((startIndex + endIndex) / 2);
13+
let temp = new Node(arr[midIndex]);
14+
temp.leftNode = constructBBST(arr, startIndex, midIndex - 1);
15+
temp.rightNode = constructBBST(arr, midIndex + 1, endIndex);
16+
return temp;
17+
}
18+
19+
function inorderDisplay(root, inOrderArr) {
20+
if (root == null) return;
21+
inorderDisplay(root.leftNode, inOrderArr);
22+
inOrderArr.push(root.data);
23+
inorderDisplay(root.rightNode, inOrderArr);
24+
}
25+
26+
let arr = [1, 2, 3, 4, 5, 6, 7, 10, 20];
27+
let tree = constructBBST(arr, 0, arr.length - 1);
28+
let inOrderArr = []
29+
inorderDisplay(tree, inOrderArr);
30+
console.log('Inorder Display - ', inOrderArr.join(', '));

0 commit comments

Comments
 (0)