Skip to content

Latest commit

 

History

History
63 lines (45 loc) · 1.51 KB

File metadata and controls

63 lines (45 loc) · 1.51 KB

108. Convert Sorted Array to Binary Search Tree

难度: Easy

刷题内容

原题连接

内容描述

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

解题方案

思路 1 - 时间复杂度: O(N) - 空间复杂度: O(1)

左右等分建立左右子树,中间节点作为子树根节点,递归该过程

  • nums为空,return None
  • nums非空,nums[n/2]为中间元素,根结点,nums[:mid]为左子树, nums[mid+1:]为右子树

beats 95.85%

class TreeNode:
    def __init__(self, x):
        self.val = x 
        self.left = None
        self.right = None
        
class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        size = len(nums)
        if size == 0:
            return None
        root = TreeNode(nums[size//2])
        root.left = self.sortedArrayToBST(nums[:size//2])
        root.right = self.sortedArrayToBST(nums[size//2+1:])
        return root