Tutorialspoint
Problem
Solution
Submissions

Sorted Array to Binary Search Tree

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

Write a Java program to convert a sorted array to a height-balanced binary search tree (BST).

Example 1
  • Input: nums = [-10,-3,0,5,9]
  • Output: [0,-3,9,-10,null,5]
  • Explanation:
    • BST structure:

      BST Tree With Neagative Values
Example 2
  • Input: nums = [1,3]
  • Output: [3,1]
  • Explanation:
    • BST structure:

      BST Tree With Normal Values
Constraints
  • 1 ≤ nums.length ≤ 10^4
  • -10^4 ≤ nums[i] ≤ 10^4
  • nums is sorted in strictly increasing order
  • Time Complexity: O(n)
  • Space Complexity: O(log n)
TreeTech MahindraApple
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.
  • Choose the middle element of the array as the root.
  • Recursively build left subtree from elements before the middle element.
  • Recursively build right subtree from elements after the middle element.
  • Return the root of the tree.

Steps to solve by this approach:

 Step 1: Check if the input array is null or empty. If so, return null.
 Step 2: Find the middle element of the array - this becomes the root of the BST.
 Step 3: Create a new TreeNode with the middle element's value.
 Step 4: Recursively construct the left subtree using the left half of the array.
 Step 5: Recursively construct the right subtree using the right half of the array.
 Step 6: Return the constructed tree root.
 Step 7: For the recursive case, if left > right, return null (base case).

Submitted Code :