Convert Sorted Array to Binary Search Tree
Question (LC.108)
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Example
Input: nums = [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5]
0
/ \
-3 9
/ /
-10 5
Another possible answer is: [0,-10,5,null,-3,null,9]
0
/ \
-10 5
/ \ / \
null -3 null 9 Analysis
Divide and conquer the array. Be careful on the even and odd case on how to divvy up the subarray.
Code
O(n) time and O(n) space
PreviousConvert Binary Search Tree to Sorted Doubly Linked ListNextConvert Sorted List to Binary Search Tree
Last updated