LC.108.Convert Sorted Array to Binary Search Tree

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC.108.Convert Sorted Array to Binary Search Tree相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

2.1.1Remove Duplicates from Sorted Arr

Sorted Union

LeetCode 1213. Intersection of Three Sorted Arrays

Java—Remove Deplicates from Sorted Array(顺序数组中去重位置)

python 二维数组排序

Count the number of occurrences in a sorted array