This should give you a balanced tree (in O(n)):
- Construct a node for the middle element in the array and return it
(this will be the root in the base case).
- Repeat from 1. on the left half of the array, assigning the return value to the left child of the root.
- Repeat from 1. on the right half of the array, assigning the return value to the right child of the root.
Java-like code:
TreeNode sortedArrayToBST(int arr[], int start, int end) {
if (start > end) return null;
// same as (start+end)/2, avoids overflow.
int mid = start + (end - start) / 2;
TreeNode node = new TreeNode(arr[mid]);
node.left = sortedArrayToBST(arr, start, mid-1);
node.right = sortedArrayToBST(arr, mid+1, end);
return node;
}
TreeNode sortedArrayToBST(int arr[]) {
return sortedArrayToBST(arr, 0, arr.length-1);
}
Code derived from here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…