二叉搜索树的定义:
首先它是有序树
此题的题目中还强调了一点,高度平衡,这就需要知道平衡二叉树的概念:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def traversal(nums, left, right):
if left > right:
return None
mid = (left + right) // 2
root = TreeNode(nums[mid])
root.left = traversal(nums, left, mid - 1)
root.right = traversal(nums, mid + 1, right)
return root
root = traversal(nums, 0, len(nums) - 1)
return root