美文网首页
【2错-2】Convert Sorted Array to Bi

【2错-2】Convert Sorted Array to Bi

作者: 7ccc099f4608 | 来源:发表于2019-01-21 01:11 被阅读2次

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

日期 是否一次通过 comment
2019-01-21 01:06 思路太僵
2019-01-22 00:00 思路太僵,对二分查找理解不够
image.png

(来源:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

关键:理解BST

  1. 非递归:TODO;
  2. 递归:使用二分查找

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;
    }
}

相关文章

网友评论

      本文标题:【2错-2】Convert Sorted Array to Bi

      本文链接:https://www.haomeiwen.com/subject/rmkqjqtx.html