一个有序数组,转化为高度平衡的二叉搜索树
每个节点的左右两个子树的高度差的绝对值不超过 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
n = len(nums)
if n == 0:
return None
if n == 1:
return TreeNode(nums[0])
tree = TreeNode(nums[n // 2])
tree.left = Solution.sortedArrayToBST("", nums[0: n // 2])
if n > 2:
tree.right = Solution.sortedArrayToBST("", nums[n // 2 + 1:])
return tree