📖 Scenario: You have a sorted list of numbers representing data that needs to be organized for fast searching. A balanced Binary Search Tree (BST) is a great way to do this because it keeps the data sorted and allows quick lookups.Imagine you are building a phone book app that needs to quickly find contacts by their phone numbers. You want to convert the sorted list of phone numbers into a balanced BST to make searching efficient.
🎯 Goal: Build a balanced Binary Search Tree (BST) from a given sorted array of numbers. The BST should be balanced, meaning the left and right subtrees of every node differ in height by no more than one.You will write code to create tree nodes, pick the middle element as the root, and recursively build left and right subtrees.
📋 What You'll Learn
Create a TreeNode class with val, left, and right properties
Use a recursive function sortedArrayToBST that takes a sorted array and returns the root of the balanced BST
Pick the middle element of the current array/subarray as the root node
Recursively build left subtree from the left half of the array
Recursively build right subtree from the right half of the array
Print the BST nodes in preorder traversal (root, left, right) to verify the structure
💡 Why This Matters
🌍 Real World
Balanced BSTs are used in databases, file systems, and search engines to organize data for fast searching and insertion.
💼 Career
Understanding how to convert sorted data into balanced trees is important for software engineers working on efficient data storage, retrieval, and algorithms.
Progress0 / 4 steps
1
Create the TreeNode class
Create a class called TreeNode with a constructor that takes a parameter val and sets this.val to it. Also initialize this.left and this.right to null.
DSA Javascript
Hint
Think of each tree node as a box holding a value and two empty slots for left and right child nodes.
2
Set up the sorted array
Create a constant array called nums with these exact values: [1, 2, 3, 4, 5, 6, 7].
DSA Javascript
Hint
This array is already sorted, which is perfect for building a balanced BST.
3
Write the recursive function to build the BST
Write a function called sortedArrayToBST that takes a parameter arr. Inside, if arr.length is 0, return null. Otherwise, find the middle index as Math.floor(arr.length / 2). Create a TreeNode with the middle element. Recursively assign root.left by calling sortedArrayToBST on the left half of the array, and root.right by calling it on the right half. Return the root node.
DSA Javascript
Hint
Use the middle element as the root to keep the tree balanced. Use array slicing to get left and right parts.
4
Print the BST nodes in preorder traversal
Write a function called preorderTraversal that takes a node. If node is null, return an empty array. Otherwise, return an array with node.val followed by the result of preorderTraversal(node.left) and then preorderTraversal(node.right). Then, create a variable root by calling sortedArrayToBST(nums). Finally, print the result of preorderTraversal(root) using console.log.
DSA Javascript
Hint
Preorder traversal visits root first, then left subtree, then right subtree. Use recursion to collect values.
Practice
(1/5)
1. What is the main goal when converting a sorted array to a balanced Binary Search Tree (BST)?
easy
A. To create a linked list from the array
B. To reverse the array elements
C. To create a BST with minimal height for efficient search
D. To sort the array again
Solution
Step 1: Understand the problem goal
The goal is to build a BST that is balanced, meaning the tree height is minimized for faster search operations.
Step 2: Recognize the importance of balance
A balanced BST ensures operations like search, insert, and delete run efficiently, typically in O(log n) time.
Final Answer:
To create a BST with minimal height for efficient search -> Option C
A. The right subtree slice should start from mid + 1, not mid
B. The base case should check for arr === null instead of length
C. The mid index calculation is incorrect
D. The root node is not created properly
Solution
Step 1: Analyze the slicing for right subtree
The right subtree should exclude the middle element already used as root, so slice should start from mid + 1.
Step 2: Identify the bug
Using arr.slice(mid) includes the middle element again in the right subtree, causing duplicate nodes and incorrect tree.
Final Answer:
The right subtree slice should start from mid + 1, not mid -> Option A
Quick Check:
Right subtree slice = arr.slice(mid + 1) [OK]
Hint: Right subtree excludes middle element: slice from mid+1 [OK]
Common Mistakes:
Including middle element in both subtrees
Wrong base case condition
Incorrect mid calculation
5. Given the sorted array [-10, -3, 0, 5, 9], what is the preorder traversal (root-left-right) of the balanced BST created by the standard algorithm?
hard
A. [0, -10, -3, 5, 9]
B. [-3, -10, 0, 5, 9]
C. [5, 0, -10, -3, 9]
D. [0, -3, -10, 9, 5]
Solution
Step 1: Build the balanced BST
Middle index = Math.floor(5/2) = 2, root = 0. Left subarray [-10, -3], length=2, mid=Math.floor(2/2)=1, left child = -3 (left of -3: [-10] mid=0 value -10; right of -3: empty). Right subarray [5, 9], length=2, mid=1, right child = 9 (left of 9: [5]; right of 9: empty).