image.pnghttps://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
(图片来源https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
)
日期 | 是否一次通过 | comment |
---|---|---|
2020-03-15 | 0 |
递归
// BST:左大右小
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null) {
return null;
}
return helper(nums, 0, nums.length-1);
}
// 二分找到给定区间中间的点
private TreeNode helper(int[] nums, int sta, int end) {
if(sta > end) {
return null;
}
int mid = sta + (end-sta)/2;
TreeNode node = new TreeNode(nums[mid]);
node.left = helper(nums, sta, mid-1);
node.right = helper(nums, mid+1, end);
return node;
}
网友评论