Given an array where elements are sorted in ascending order, convert it to a height balanced BST. |
Hint: ![]() An example of a height-balanced tree. A height-balanced tree is a tree whose subtrees differ in height by no more than one and the subtrees are height-balanced, too. Solution: You would pick the middle element from the sorted array in each iteration. You then create a node in the tree initialized with this element. After the element is chosen, what is left? Could you identify the sub-problems within the problem? There are two arrays left -- The one on its left and the one on its right. These two arrays are the sub-problems of the original problem, since both of them are sorted. Furthermore, they are subtrees of the current node's left and right child.
Further Thoughts: |
Use recursive method to solve this question.
|
use recursive function
|
link
This answer is marked "community wiki".
|
public class Solution {
} |
TreeNode *sortedArrayToBST(vector<int> &num) {
|
|
|
|