前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LEETCODE】模拟面试-108-Convert Sorted Array to Binary Search Tree

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

作者头像
杨熹
发布2018-04-03 15:01:27
6500
发布2018-04-03 15:01:27
举报
文章被收录于专栏:杨熹的专栏

图源:新生大学

题目:

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

代码语言:javascript
复制
/**
 * 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;
    }
    
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.01.05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目:
  • 分析:
  • Java
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档