sortedArray_to_bst.py 436 B

1234567891011121314151617181920
  1. from typing import List, Optional
  2. from tree import TreeNode
  3. class Solution:
  4. def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
  5. if not nums:
  6. return
  7. mid = len(nums) // 2
  8. root = TreeNode(nums[mid])
  9. if mid == 0:
  10. return root
  11. root.left = self.sortedArrayToBST(nums[:mid])
  12. root.right = self.sortedArrayToBST(nums[mid + 1:])
  13. return root