https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
日期 | 是否一次通过 | comment |
---|---|---|
2019-01-21 01:06 | 否 | 思路太僵 |
2019-01-22 00:00 | 否 | 思路太僵,对二分查找理解不够 |
(来源:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)
关键:理解BST
- 非递归:TODO;
- 递归:使用二分查找
1. 非递归
2.递归
class Solution {
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;
}
}
网友评论