继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【LEETCODE】模拟面试-108-Convert Sorted Array to Binary Search Tree

Alice嘟嘟
关注TA
已关注
手记 209
粉丝 75
获赞 279

图源:新生大学

题目:

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

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.


分析:

Input: So we're given a sorted array in ascending order.
**Output: ** To return the root of a Binary Search Tree.

The corner case is when the input array is null or empty, then we will return null.

To build a tree, we need to firstly find the root.

And since it's a BST, which means the difference between the height of left tree and right tree is no more than 1, the middle in the array will be taken as the root.

And the left part will construct the left tree, right part will be the right tree.

Then we move to the next level, again, we'll first find the parent which will be the middle in the left part of array, and the right tree will be processed as well.

According to this procedure, it's obvious that we can use Recursion to deal with this problem.

At each level, we find the middle of current array period.
For next level, we will pass current 'middle' as left boundary and right boundary to right tree or left tree, until we move to an interval where its 'start' index is larger then 'end' index.

Here we got the code as followed:

The Time complexity is O(n), since we traverse every data in the array.
The Space complexity is O(1), since we haven't applied any data structure.
or we can say O(logn), since the recursion has its own stack space.


Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */public class Solution {    public TreeNode sortedArrayToBST(int[] array){        //corner case
        if ( array == null || array.length == 0 )            return null;        
        //core logic
        int n = array.length;        return helper(array, 0, n-1);
    }    
    private TreeNode helper(int[] array, int start, int end){        //base case
        if ( start > end )            return null;        
        //current
        int mid = start + (end - start) / 2;
        TreeNode root = new TreeNode( array[mid] );        
        //next
        root.left = helper( array, start, mid - 1 );
        root.right = helper( array, mid + 1, end );        
        return root;
    }
    
}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP