zoukankan      html  css  js  c++  java
  • 108. Convert Sorted Array to Binary Search [Python]

    108. Convert Sorted Array to Binary Search

    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.

    给定一个升序的矩阵,将它转换成一棵平衡二叉树。

    其中,平衡二叉树是指树中每个节点子树高度差的绝对值不超过1的树。

    思路:由于左右高度差的绝对值不能超过1,所以树根节点应选择升序列表中间的元素,即nums[len(nums)//2]。

    该元素前面的元素(比根节点小的元素)同理递归地放入左子树;后面的元素递归地放入右子树。

    最后返回各个节点。

    代码

    class Solution:
        def sortedArrayToBST(self, nums):
            """
            @param type nums: List[int]
            @param rtype: TreeNode
            """
            if nums == None:
                return
            if len(nums) == 1:
                return nums[0]
            root = nums[len(nums)//2]
            self.sortedArrayToBST(nums[:len(nums)//2])
            self.sortedArrayToBST(nums[len(nums)//2+1:])
            return root
    
  • 相关阅读:
    css定位
    题解 P2345 【奶牛集会】
    浅谈主席树
    浅谈Manacher算法
    CSP2019 游记
    P5025 [SNOI2017]炸弹
    浅谈2-SAT
    DAY 5模拟赛
    DAY 3
    Luogu P2915 [USACO08NOV]奶牛混合起来
  • 原文地址:https://www.cnblogs.com/wyz-2020/p/12386366.html
Copyright © 2011-2022 走看看