Convert a Binary Tree to a Binary Search Tree using JavaScript
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that it keeps the original structure of the Binary Tree.
Example: To demonstrate the conversion of the Binary Tree to the Binary Search Tree.
Input:
10
/ \
2 7
/ \
8 4
Output:
8
/ \
4 10
/ \
2 7
Approach
In this approach we are using Inorder Traversal and Sorting. To convert a binary tree to a BST, define a Node class and implement helper functions: newNode for node creation, printInorder for traversal, storeInorder to store inorder traversal in an array, and arrayToBST to update the tree with sorted values. In binaryTreeToBST , count the nodes, store and sort the inorder traversal, and update the tree. Finally, create a sample tree, convert it, and print its inorder traversal.
Example: The example below illustrates the Conversion of a binary tree to a binary search tree using JavaScript.
class Node {
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
let index = 0;
function newNode(data) {
let temp = new Node(data);
return temp;
}
function printInorder(node) {
if (node == null)
return;
printInorder(node.left);
console.log(node.data + " ");
printInorder(node.right);
}
function arrayToBST(arr, root) {
// Base Case
if (root == null)
return;
arrayToBST(arr, root.left);
root.data = arr[index];
index++;
arrayToBST(arr, root.right);
}
function storeInorder(node, inorder) {
// Base Case
if (node == null)
return inorder;
storeInorder(node.left, inorder);
inorder[index] = node.data;
index++;
storeInorder(node.right, inorder);
}
function countNodes(root) {
if (root == null)
return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}
function binaryTreeToBST(root) {
if (root == null)
return;
let n = countNodes(root);
let arr = new Array(n);
arr.fill(0);
storeInorder(root, arr);
arr.sort(function (a, b) { return a - b });
index = 0;
arrayToBST(arr, root);
}
let root = null;
root = newNode(10);
root.left = newNode(30);
root.right = newNode(15);
root.left.left = newNode(20);
root.right.right = newNode(5);
binaryTreeToBST(root);
console.log("Following is Inorder Traversal of the converted BST: ");
printInorder(root);
Output
Following is Inorder Traversal of the converted BST: 5 10 15 20 30
Time Complexity: O(n*logn)
Auxiliary Space: O(n)