zoukankan      html  css  js  c++  java
  • 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 ;
        }


  • 相关阅读:
    HTML: vertical algin Big/small div in same row (bootstrap)
    unix时间转换
    chrome工具分析
    DNF 包管理器
    安装nodejs
    location属性解释
    angular深入理解途径
    ui-router与ngRoute
    angular $location服务获取url
    Python文件操作
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8495669.html
Copyright © 2011-2022 走看看