Solve 108. Convert Sorted Array to Binary Search Tree
This commit is contained in:
parent
75ef39813b
commit
cdcff5d91d
20
python/108_convert_sorted_array_to_binary_search_tree.py
Normal file
20
python/108_convert_sorted_array_to_binary_search_tree.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
# 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]:
|
||||||
|
if nums == []:
|
||||||
|
return None
|
||||||
|
|
||||||
|
mid = len(nums)//2
|
||||||
|
left = nums[:mid]
|
||||||
|
right = nums[mid+1:]
|
||||||
|
|
||||||
|
head = TreeNode(nums[mid])
|
||||||
|
head.left = self.sortedArrayToBST(left)
|
||||||
|
head.right = self.sortedArrayToBST(right)
|
||||||
|
return head
|
Loading…
Reference in New Issue
Block a user