Convert a Sorted Array into a Binary Search Tree(BST) (Leetcode 108)
Problem Link: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
n=len(nums)
if(n<=0):
return
mid=n//2
data=nums[mid]
leftchild=self.sortedArrayToBST(nums[:mid])
rightchild=self.sortedArrayToBST(nums[mid+1:])
rootnode=TreeNode(data)
rootnode.left=leftchild
rootnode.right=rightchild
return rootnode
Last updated