Convert Sorted Array to Binary Search Tree
TreesDFS
Problem Statement
Given an integer array `nums` where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Example
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Solution: Depth-First Search (DFS)
The problem can be solved efficiently using a recursive Depth-First Search. We can use the fact that the array is sorted to our advantage.
Algorithm Steps
- The middle element of the array will be the root of the BST.
- The left half of the array will form the left subtree, and the right half will form the right subtree.
- Recursively call the function on the left and right halves of the array to build the subtrees.
-10
0
-3
1
0
2
5
3
9
4
Processing [-10, -3, 0, 5, 9]. Mid is 0.
Convert Sorted Array to BST Solution