# 108. Convert Sorted Array to Binary Search Tree

    public TreeNode sortedArrayToBST(int[] nums) {
int length=nums.length;
if(length==0)
return null;
if(length==1)
return new TreeNode(nums[0]);
int pos=length/2;
TreeNode root=new TreeNode(nums[pos]);
root.left=sortedArrayToBST(nums,0,pos-1);
if(length>2)
root.right=sortedArrayToBST(nums,pos+1,length-1);
return root;
}

private TreeNode sortedArrayToBST(int[] nums,int begin,int end) {
int length=end-begin+1;
int pos=length/2+begin;
TreeNode root=new TreeNode(nums[pos]);
if(pos-begin==1)
root.left=new TreeNode(nums[begin]);
else if(pos-begin>1)
root.left=sortedArrayToBST(nums,begin,pos-1);
if(end-pos==1)
root.right=new TreeNode(nums[end]);
else if(end-pos>1)
root.right=sortedArrayToBST(nums,pos+1,end);
return root;
}

 public TreeNode sortedArrayToBST(int[] nums) {
return buildTree(nums, 0, nums.length - 1);
}

private TreeNode helper(int[] nums, int start, int end) {
if (start > end) {
System.out.println(start + ", " + end);
return null;
}

int mid = (end + start) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, start, mid - 1);
root.right = helper(nums, mid + 1, end);

return root;
}

private TreeNode buildTree(int[] num, int start, int end) {
if (start > end) {
return null;
}

TreeNode node = new TreeNode(num[(start + end) / 2]);
node.left = buildTree(num, start, (start + end) / 2 - 1);
node.right = buildTree(num, (start + end) / 2 + 1, end);
return node;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120