<script>
class node {
constructor() {
this
.key = 0;
this
.left =
this
.right =
null
;
}
}
var
index = 0;
function
newNode(item) {
var
temp =
new
node();
temp.key = item;
temp.left = temp.right =
null
;
return
temp;
}
function
insert( node , key) {
if
(node ==
null
)
return
newNode(key);
if
(key < node.key)
node.left = insert(node.left, key);
else
if
(key > node.key)
node.right = insert(node.right, key);
return
node;
}
function
sizeOfTree( root) {
if
(root ==
null
) {
return
0;
}
var
left = sizeOfTree(root.left);
var
right = sizeOfTree(root.right);
return
(left + right + 1);
}
function
storeInorder( root , inOrder) {
if
(root ==
null
) {
return
;
}
storeInorder(root.left, inOrder);
inOrder[index++] = root.key;
storeInorder(root.right, inOrder);
}
function
getSplittingIndex(inOrder , k) {
for
(i = 0; i < index; i++) {
if
(inOrder[i] >= k) {
return
i - 1;
}
}
return
index - 1;
}
function
createBST(inOrder , start , end) {
if
(start > end) {
return
null
;
}
var
mid = parseInt((start + end) / 2);
var
t = newNode(inOrder[mid]);
t.left = createBST(inOrder, start, mid - 1);
t.right = createBST(inOrder, mid + 1, end);
return
t;
}
function
inorderTrav( root) {
if
(root ==
null
)
return
;
inorderTrav(root.left);
document.write(root.key +
" "
);
inorderTrav(root.right);
}
function
splitBST( root , k) {
document.write(
"Original BST : "
);
if
(root !=
null
) {
inorderTrav(root);
}
else
{
document.write(
"null"
);
}
document.write();
var
numNode = sizeOfTree(root);
var
inOrder = Array(numNode + 1).fill(0);
index = 0;
storeInorder(root, inOrder);
var
splitIndex = getSplittingIndex(inOrder, k);
var
root1 =
null
;
var
root2 =
null
;
if
(splitIndex != -1)
root1 = createBST(inOrder, 0, splitIndex);
if
(splitIndex != (index - 1))
root2 = createBST(inOrder, splitIndex + 1, index - 1);
document.write(
"<br/>First BST : "
);
if
(root1 !=
null
) {
inorderTrav(root1);
}
else
{
document.write(
"null"
);
}
document.write();
document.write(
"<br/>Second BST : "
);
if
(root2 !=
null
) {
inorderTrav(root2);
}
else
{
document.write(
"null"
);
}
}
var
root =
null
;
root = insert(root, 5);
insert(root, 3);
insert(root, 2);
insert(root, 4);
insert(root, 7);
insert(root, 6);
insert(root, 8);
var
k = 5;
splitBST(root, k);
</script>