JavaScript Program to Convert Sorted Array to BST
Last Updated :
30 Apr, 2024
Given a sorted array, convert it into a binary search tree (BST). A binary search tree is a binary tree where the value of each node is larger than the values in its left subtree and smaller than the values in its right subtree.
Example:
Input: sorted array= [2, 4, 7, 9, 10]
Output: Binary Search Tree
7
/ \
4 9
/ \
2 10
Below are different approaches to convert Sorted Array to BST in JavaScript.
Recursive Approach
In the recursive approach, we start by finding the middle element of the sorted array. This element becomes the root of the current subtree. We then recursively build the left subtree using the left part of the array and the right subtree using the right part of the array. This process continues until we have processed all elements of the array.
Example: This example uses recursive approach to convert Sorted Array to BST.
JavaScript
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function sortedArrayToBST(nums, start = 0, end = nums.length - 1) {
if (start > end) return null;
const mid = Math
.floor((start + end) / 2);
const root = new TreeNode(nums[mid]);
root
.left = sortedArrayToBST(nums, start, mid - 1);
root
.right = sortedArrayToBST(nums, mid + 1, end);
return root;
}
function inorderTraversal(node) {
if (node) {
inorderTraversal(node.left);
console.log(node.value);
inorderTraversal(node.right);
}
}
// Example usage
const nums = [2, 4, 7, 9, 10];
const root = sortedArrayToBST(nums);
// Print the BST
inorderTraversal(root);
Time Complexity: O(n)
Space Complexity: O(n)
Iterative approach using Stack
In this approach, we are using a stack to iteratively build a binary search tree (BST) from a sorted array. We start by pushing an initial range representing the entire array onto the stack. Then, while the stack is not empty, we pop a range and create a node for the middle element of that range. If there are elements to the left or right of the middle element, we push new ranges for those subarrays onto the stack. This process continues until the stack is empty.
Example: This example uses stack to iteratively build a binary search tree from sorted array.
JavaScript
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function sortedArrayToBST(nums) {
if (!nums.length) return null;
const stack =
[
{
start: 0,
end: nums.length - 1,
parent: null,
isLeft: true
}
];
let root = null;
while (stack.length) {
const {
start,
end,
parent,
isLeft
} = stack
.pop();
const mid = Math
.floor((start + end) / 2);
const newNode = new TreeNode(nums[mid]);
if (!root) {
root = newNode;
}
if (parent) {
if (isLeft) parent
.left = newNode;
else parent
.right = newNode;
}
if (start < mid) {
stack.push
(
{
start,
end: mid - 1,
parent: newNode,
isLeft: true
}
);
}
if (end > mid) {
stack
.push
(
{
start: mid + 1,
end,
parent: newNode,
isLeft: false
}
);
}
}
return root;
}
function inorderTraversal(node) {
if (node) {
inorderTraversal(node.left);
console.log(node.value);
inorderTraversal(node.right);
}
}
// Example usage
const nums = [20, 40, 70, 90, 100];
const root = sortedArrayToBST(nums);
// Print the BST
inorderTraversal(root);
Time Complexity: O(n)
Space Complexity: O(n).
Similar Reads
JavaScript Program for Insertion Sort What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
Java Program to Sort an ArrayList ArrayList is the class provided in the Collection framework. In Java, the collection framework is defined in java.util package. ArrayList is used to dynamically stores the elements. It is more flexible than an array because there is no size limit in ArrayList. ArrayList stores the data in an unorder
6 min read
Java Program to Construct a Binary Search Tree Binary Search Tree (BST) is the widely used data structure in computer science, primarily known for the efficient search, insertion, and deletion operations. It is the type of binary tree where each node has at most two children, referred to as the left child and the right child. Binary Search Tree
6 min read
Java Program to Sort the Elements of an Array in Ascending Order Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort()
2 min read
Javascript Program For Sorting An Array Of 0s, 1s and 2s Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2}Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}Output: {0, 0, 0, 0, 0
5 min read
Java Program to Sort ArrayList of Custom Objects By Property Here we are going to look at the approach of sorting an ArrayList of custom objects by using a property. Approach: 1. Create a getter function which returns the value stored in the class variable. 2. Create a list and use sort() function which takes the values of the list as arguments and compares t
2 min read