108. Convert Sorted Array to Binary Search Tree

Easy

Problem:

Given an integer array nums where the elements are sorted in ascending order, convert it to a binary search tree.

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

Solution:

To create a BST, you just need to keep breaking down a sorted array using binary search. Obviously, it won't work if the array isn't sorted. This is because binary search is an algorithm that can find any value in Olog(n)Olog(n) time when used on a sorted array.

# 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 not nums:
            return None
        
        mid = 

        # Divide-and-Conquer
        node = TreeNode(nums[mid])
        node.left = self.sortedArrayToBST(nums[:mid])
        node.right = self.sortedArrayToBST(nums[mid + 1:])

        return node

Last updated