Tutorialspoint
Problem
Solution
Submissions

Sorted Array to Binary Search Tree

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to convert a sorted array in ascending order into a height-balanced binary search tree (BST). A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Example 1
  • Input: nums = [-10, -3, 0, 5, 9]
  • Output: [0, -3, 9, -10, null, 5]
  • Explanation:
    • Choose the middle element 0 as the root of the BST.
    • The elements less than 0 ([-10, -3]) form the left subtree.
    • The elements greater than 0 ([5, 9]) form the right subtree.
    • Recursively, choose -3 as the root of the left subtree and 9 as the root of the right subtree.
    • Continue recursively until all elements are placed.
    • The final tree will be:

      Binary Search Tree with Negative Values 
Example 2
  • Input: nums = [1, 3]
  • Output: [3, 1]
  • Explanation:
    • Choose the middle element 3 as the root of the BST.
    • The elements less than 3 ([1]) form the left subtree.
    • There are no elements greater than 3, so the right subtree is empty.
    • The final tree will be: 

      Binary Search Tree with Positive Values
Constraints
  • The input array is sorted in ascending order.
  • The array elements are all distinct integers.
  • The array may have a length from 0 to 10^4.
  • Time Complexity: O(n), where n is the number of elements in the array.
  • Space Complexity: O(log n) for the recursion stack.
ArraysTreeIBMApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach to build the BST.
  • Find the middle element of the array and make it the root node.
  • Recursively build the left subtree using the left portion of the array.
  • Recursively build the right subtree using the right portion of the array.
  • Ensure the BST property is maintained (all left descendants ≤ root < all right descendants).
  • Pay attention to the base case when the array is empty.
  • Use the divide-and-conquer technique for efficiency.

Steps to solve by this approach:

 Step 1: Create a helper function that builds the BST recursively.

 Step 2: For each recursive call, find the middle element of the current subarray.
 Step 3: Create a new tree node with the middle element as its value.
 Step 4: Set the left child of this node to be the BST created from the left part of the subarray.
 Step 5: Set the right child of this node to be the BST created from the right part of the subarray.
 Step 6: Handle the base case where the subarray is empty (return NULL).
 Step 7: Return the root of the constructed BST.

Submitted Code :