108. 将有序数组转换为二叉搜索树
小于 1 分钟
108. 将有序数组转换为二叉搜索树简单
解法:递归
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
int i = nums.length / 2;
TreeNode res = new TreeNode(nums[i]);
res.left = build(nums,0,i - 1);
res.right = build(nums,i + 1,nums.length - 1);
return res;
}
public TreeNode build(int[] nums, int left, int right) {
if(left > right) return null;
else {
int i = (left + right) / 2;
TreeNode node = new TreeNode(nums[i]);
node.left = build(nums,left,i - 1);
node.right = build(nums,i + 1,right);
return node;
}
}
}
Powered by Waline v2.15.5