Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Explanation: [0,-10,5,null,-3,null,9] is also accepted.
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
nums is sorted in a strictly increasing order.The problem requires us to convert a sorted array into a height-balanced binary search tree (BST). The key observation here is that for the BST to be height-balanced, the middle of the array should be selected as the root. This condition ensures that the heights of the subtrees do not vary by more than one. The left half of the array would then form the left subtree, and the right half would form the right subtree. This naturally suggests a recursive divide-and-conquer algorithm:
null.While the recursive approach is intuitive, using an iterative approach can help us manage large input sizes or environments where stack depth is limited. For an iterative solution, we can use a stack to simulate the recursive calls. The stack will store not only the array indices but also pointers to the parent nodes to connect the newly created nodes as either left or right children.
node is the parent node, and left, right are the current subarray bounds.