[leetCode]108.将有序数组转化为二叉搜索树
解法中序遍历-递归
选择不同的中间位置可以产生不同的高度平衡二叉搜索树
- lo +(hi - lo)/2 或 (lo + hi)/2 选择中间位置左边数字作为根节点
- lo+(hi - lo)/2 + 1 或 (lo + hi +1)/2 选择中间位置右边数字作为根节点
- lo+(hi - lo)/2 + rand.nextInt(2) 或 (lo + hi +rand.nextInt(2))/2 选择中间位置任意数字作为根节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
int mid =nums.length/2;
if(nums.length == 0)return null;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(Arrays.copyOfRange(nums,0, mid));
root.right = sortedArrayToBST(Arrays.copyOfRange(nums,mid+1, nums.length));
return root;
}
}
上面的递归用了Arrays.copyOfRange
所以要慢,下面递归使用两个指针所以要快
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return dfs(nums, 0, nums.length-1);
}
public TreeNode dfs(int[] nums, int lo, int hi){
if(hi<lo) return null;
int mid = lo + (hi - lo)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = dfs(nums, lo, mid-1);
root.right = dfs(nums, mid+1, hi);
return root;
}
}