Problem
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9]
,
One possible answer is: [0,-3,9,-10,null,5]
, which represents the following height balanced BST:
1 |
|
Explanation
- If we use in-order traversal of a binary search tree, then we can get a sorted array. So, if we have a sorted array, then the middle element must be the root of the tree, and we can divide the array into two parts from 0 to mid-1 to find the left-subtree and mid+1 to array.length-1 to find the right-subtree. So, this problem can be sorted using binary search method.
Solution
1 |
|