Tutorialspoint
Problem
Solution
Submissions

Sorted Array to a Binary Search Tree

Certification: Intermediate Level Accuracy: 100% Submissions: 1 Points: 12

Write a C++ program to implement the sortedArrayToBST(vector<int>& nums) function, which converts a sorted array into a height-balanced binary search tree (BST).

Example 1
  • Input: nums = [-10,-3,0,5,9]
  • Output: [0,-3,9,-10,null,5]
  • Explanation:
    • The output represents the following height-balanced BST:

      Binary Search Tree with Root Node 0
Example 2
  • Input: nums = [1,3]
  • Output: [3,1]
  • Explanation:
    • The output represents the following height-balanced BST:

      Binary Search Tree with Root Node 3
Constraints
  • 1 ≤ nums.length ≤ 10^4
  • -10^4 ≤ nums[i] ≤ 10^4
  • nums is sorted in a strictly increasing order
  • Time Complexity: O(n)
  • Space Complexity: O(log n) for the recursion stack
ArraysTreeWalmartApple
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 divide-and-conquer approach to build the BST
  • The middle element of the array will be the root of the BST
  • The left subarray will form the left subtree, and the right subarray will form the right subtree
  • Recursively apply this procedure to build the entire tree

Steps to solve by this approach:

 Step 1: Use a divide-and-conquer approach to build a height-balanced BST.
 Step 2: Find the middle element of the array to use as the root of the tree.
 Step 3: Create a new TreeNode with the middle element as its value.
 Step 4: Recursively build the left subtree using the elements to the left of the middle.
 Step 5: Recursively build the right subtree using the elements to the right of the middle.
 Step 6: Return the root of the constructed BST.
 Step 7: Base case: if the subarray is empty (left > right), return null.

Submitted Code :