Python solution with detailed explanation


  • 0
    G

    Solution

    Convert Sorted Array to Binary Search Tree https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/?tab=Description

    Algorithm

    1. Simple divide and conquer.
    2. Just make sure to get edge cases right:
      if s > e:
      return None
      mid = s + ((e-s)>>1)
    class Solution(object):
        def sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            """
            tnode = self.helper(nums, 0, len(nums)-1)
            return tnode
        
        def helper(self, nums, s, e):
            if s > e:
                return None
            mid = s + ((e-s)>>1)
            tnode = TreeNode(nums[mid])
            tnode.left = self.helper(nums, s, mid-1)
            tnode.right = self.helper(nums, mid+1, e)
            return tnode
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.