
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:
- The output represents the following height-balanced BST:
Example 2
- Input: nums = [1,3]
- Output: [3,1]
- Explanation:
- The output represents the following height-balanced BST:
- The output represents the following height-balanced BST:
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
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 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