Question:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
if(num.length==0) return null;
if(num.length==1) return new TreeNode(num[0]);
int mid = num.length/2;
TreeNode root = new TreeNode(num[mid]);
int lenleft = mid;
int lenright = num.length-mid-1;
int[] left = new int[lenleft];
int[] right = new int[lenright];
for(int i=0; i<lenleft; i++) left[i] = num[i];
for(int i=mid+1; i<num.length; i++) right[i-mid-1] = num[i];
root.left = sortedArrayToBST(left);
root.right = sortedArrayToBST(right);
return root;
}
}
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
if(num.length==0)
return null;
int mid = num.length/2;
TreeNode root = new TreeNode(num[mid]);
int leftLen = mid;
int rightLen = num.length-mid-1;
int[] left = new int[leftLen];
int[] right = new int[rightLen];
System.arraycopy(num,0,left,0,leftLen);
System.arraycopy(num,mid+1,right,0,rightLen);
root.left = sortedArrayToBST(left);
root.right = sortedArrayToBST(right);
return root;
}
}