Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
LeetCode-108: Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
In the below mentioned example, the input array [-10,-3,0,5,9]
can be represented as either [0,-3,9,-10,null,5]
or [0,-10,5,null,-3,null,9]
.
The problem can be solved using recursion.
The base case for the recursion is when the left index is greater than the right index.
Here is a java implementation of the above approach:
public TreeNode sortedArrayToBST(int[] nums) {
return build(nums, 0, nums.length -1);
}
private TreeNode build(int[] nums, int start, int end){
if(start <= end){
int mid = start + (end - start)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = build(nums, start, mid-1);
root.right = build(nums, mid+1, end);
return root;
}
return null;
}
The time complexity for the above approach is $O(n)$ where $n$ is the number of elements in the array. The space complexity is $O(\log n)$ due to the recursion stack associated with a height balanced tree.
Be notified of new posts. Subscribe to the RSS feed.