Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

 

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def sortedArrayToBST(self, nums):
10         """
11         :type nums: List[int]
12         :rtype: TreeNode
13         """
14         if not nums:
15             return None
16 
17         mid = len(nums) // 2
18 
19         root = TreeNode(nums[mid])
20         root.left = self.sortedArrayToBST(nums[:mid])
21         root.right = self.sortedArrayToBST(nums[mid+1:])
22 
23         return root

  mid = (len(nums)-1) // 2  也是正确的

posted on 2017-03-15 19:03  Ci_pea  阅读(104)  评论(0编辑  收藏  举报