题目描述
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
分析
参考:LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
只是根结点为mid,核心代码如下:
int mid = (start + end) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = buildBST(start, mid);
root.right = buildBST(mid + 1, end);
代码
int[] nums;
public TreeNode sortedArrayToBST(int[] nums) {
this.nums = nums;
return buildBST(0, nums.length);
}
TreeNode buildBST(int start, int end) {
if (start >= end) {
return null;
}
int mid = (start + end) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = buildBST(start, mid);
root.right = buildBST(mid + 1, end);
return root;
}