108. Convert Sorted Array to Bin
2019-03-05 本文已影响0人
苏州城外无故人
image.png
思路:递归,二分查找
要把一个数组变为二分查找树,数组中间点就是根节点,依次递归构造左右子树。
public static TreeNode sortedArrayToBST(int[] nums) {
if (nums.length == 0) {
return null;
}
TreeNode head = helper(nums, 0, nums.length - 1);
return head;
}
public static TreeNode helper(int[] nums, int low, int high) {
if (low > high) {
return null;
}
int mid = (low + high) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, low, mid -1);
root.right = helper(nums, mid + 1, high);
return root;
}