码迷,mamicode.com
首页 > 其他好文 > 详细

LC.108.Convert Sorted Array to Binary Search Tree

时间:2018-03-03 11:00:03      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:amp   div   desc   etc   turn   script   nec   bin   order   

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

0
/ \
-3 9
/ /
-10 5


time: o(n) space: o(height)
pre order: 先弄自己, 再管下面的兄弟
public TreeNode sortedArrayToBST(int[] nums) {
        if (nums  == null || nums.length ==0 )return null ;
        int left = 0, right = nums.length -1 ;
        return helper(nums, left, right);
    }

    //everytime create the root and connect to left and right
    private TreeNode helper(int[] nums, int left, int right) {
        int mid = left + (right - left) /2 ;
        TreeNode node = new TreeNode(nums[mid]) ;
        if (mid+ 1<=right){
            node.right = helper(nums, mid+1, right) ;
        }
        if (mid -1 >= left){
            node.left = helper(nums, left, mid-1) ;
        }
        //going down and repeat
        return node ;
    }

 



LC.108.Convert Sorted Array to Binary Search Tree

标签:amp   div   desc   etc   turn   script   nec   bin   order   

原文地址:https://www.cnblogs.com/davidnyc/p/8495669.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!