将有序数组转换为二叉搜索树-二叉树108-python

python

# 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]):
        if not nums:
            return None

        n = len(nums)
        mid = n // 2

        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])

        return root
上一篇:Leetcode 108


下一篇:【leetcode】108:将有序数组转化为二叉搜索树