Skip to content

108 convert sorted array to binary search tree

108. Convert Sorted Array to Binary Search Tree

题目: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

难度: Medium

思路:

递归

  • nums为空,return None
  • nums非空,nums[n/2]为中间元素,根结点,nums[:mid]为左子树, nums[mid+1:]为右子树
class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None
        if nums:
            mid = len(nums) / 2
            root = TreeNode(nums[mid])
            root.left = self.sortedArrayToBST(nums[:mid])
            root.right = self.sortedArrayToBST(nums[mid+1:])
            return root


回到顶部