From cdcff5d91dac0fd242d9102e513e76e6ca34bd04 Mon Sep 17 00:00:00 2001 From: Kiril Kovachev Date: Fri, 8 Mar 2024 20:08:51 +0000 Subject: [PATCH] Solve 108. Convert Sorted Array to Binary Search Tree --- ...vert_sorted_array_to_binary_search_tree.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 python/108_convert_sorted_array_to_binary_search_tree.py diff --git a/python/108_convert_sorted_array_to_binary_search_tree.py b/python/108_convert_sorted_array_to_binary_search_tree.py new file mode 100644 index 0000000..5121abe --- /dev/null +++ b/python/108_convert_sorted_array_to_binary_search_tree.py @@ -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