Tutorialspoint
Problem
Solution
Submissions

Sorted Array to a Balanced Binary Search Tree.

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

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

Example 1
  • Input: nums = [-10, -3, 0, 5, 9]
  • Output: [0, -3, 9, -10, null, 5]
  • Explanation:
    • The balanced BST would look like:

      Sorted arraay with root node 0
Example 2
  • Input: nums = [1, 3]
  • Output: [3, 1]
  • Explanation:
    • The balanced BST would look like:

      Sorted arraay with root node 3
Constraints
  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in ascending order
  • Time Complexity: O(n)
  • Space Complexity: O(log n)
ArraysTreeHCL TechnologiesApple
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 recursion to build the balanced BST
  • Choose the middle element of the array as the root
  • Recursively build left subtree with elements before the middle
  • Recursively build right subtree with elements after the middle
  • Return the root of the balanced BST

Steps to solve by this approach:

 Step 1: Define a recursive function that takes the array and indices for left and right boundaries.
 Step 2: Find the middle element of the current array segment.
 Step 3: Create a new tree node with the middle element as the value.
 Step 4: Recursively build the left subtree using elements before the middle.
 Step 5: Recursively build the right subtree using elements after the middle.
 Step 6: Return the root node to construct the complete BST.
 Step 7: Handle base cases (empty array or invalid boundaries).

Submitted Code :