Given an integer array nums sorted in ascending order, convert it to a height-balanced binary search tree.
nums = [-10,-3,0,5,9][0,-3,9,-10,null,5]nums = [1,3][3,1] or [1,null,3]nums = [1,2,3,4,5,6,7][4,2,6,1,3,5,7]lo > hi → return nullmid = lo + (hi − lo) / 2node = new TreeNode(nums[mid])node.left = build(lo, mid−1)node.right = build(mid+1, hi)Choosing the midpoint as root ensures the left and right subtrees have sizes that differ by at most 1. Since the array is sorted, elements to the left of mid are all smaller (BST left subtree) and elements to the right are all larger (BST right subtree). Applying this rule recursively at every level guarantees a height-balanced BST where |height(left) − height(right)| ≤ 1 at every node.
Inserting the values one by one, in sorted order, makes a chain going to the right. That is a valid search tree, but it is completely unbalanced.
Pick the middle element as the root. Everything to its left is smaller, so it builds the left subtree. Everything to its right is bigger, so it builds the right subtree. Because both halves have almost the same size, the tree stays balanced. Repeat the same rule on each half until a range is empty.
The middle element is the root, and each half becomes a subtree. Choosing the middle is what keeps the tree balanced.
Run the animation above on your own input, or watch the 2:06 video explanation of Convert Sorted Array to Binary Search Tree with a dry run and Java code.