将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。(一开始没思路,然后看了一下官方题解,稀里糊涂就做出来了,我也蒙了)
# Definition for a binary tree node.
class TreeNode(object):
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
"""
start = 0
end = len(nums)
mid = (start + end) // 2
if start >= end:
return
root = TreeNode(nums[mid])
left = self.sortedArrayToBST(nums[0: mid])
right = self.sortedArrayToBST(nums[mid + 1: end])
if left:
root.left = left
if right:
root.right = right
return root
if __name__ == '__main__':
s1 = Solution()
nums = [-10, -3, 0, 5, 9]
root = s1.sortedArrayToBST(nums)
print("gfsdg")