- 题目:给定有序数组,将有序数组转成二叉平衡树
- 难度:Easy
- 思路:根据二叉平衡树的性质,可采用二分查找来确定节点
- 代码:
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null || nums.length == 0){
return null;
}
return helper(nums, 0, nums.length-1);
}
public TreeNode helper(int[] nums, int left, int right){
if(left <= right){
int mid = left + (right-left)/2;
TreeNode node = new TreeNode(nums[mid]);
node.left = helper(nums, left, mid-1);
node.right = helper(nums, mid+1, right);
return node;
}else{
return null;
}
}
}