您的位置:首页 > 职场人生

leetcode Convert Sorted Array to Binary Search Tree 2.20 难度系数2

2014-01-27 12:48 477 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试 leetcode java