
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:
- Choose the middle element 0 as the root of the BST.
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:
- Choose the middle element 3 as the root of the BST.
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.
Editorial
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. |
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.