zoukankan      html  css  js  c++  java
  • leetcode_108. 将有序数组转换为二叉搜索树

    将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
    
    本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
    
    示例:
    
    给定有序数组: [-10,-3,0,5,9],
    
    一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
    
          0
         / 
       -3   9
       /   /
     -10  5
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    class Solution:
        def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
            def helper(start :int ,end:int)->TreeNode:
                if start>end :
                    return None
                middle=(start+end)//2
                root=TreeNode(nums[middle])
                root.left=helper(start,middle-1)
                root.right=helper(middle+1,end)
                return root
                
            return helper(0,len(nums)-1)
    
  • 相关阅读:
    Python内存管理机制
    哈希表(散列表)
    Python面向对象三大特性
    Python 面向对象继承
    Python面向对象 类的空间问题
    面向对象初识
    增量式爬虫
    分布式爬虫
    crawlscrapy框架
    HTML
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14051757.html
Copyright © 2011-2022 走看看