cracking the code interview convert array to BST Python

Given a sorted array with unique interger elements write an algorithm to create a binary search tree with minimal height

arr=[10,9,8,7,6,5,4,3,2,1]


we recursively build the tree based on the array, because it is sorted, we can do re arrangement based on the nodes.

 
 
def arrtoBST(arr,start,end):
    if start>end:
        return None
    mid=start+(end-start)/2
    node=TreeNode(arr[mid])
    node.left=arrtoBST(arr,start,mid-1)
    node.right=arrtoBST(arr,mid+1,end)
    return node
newnode=arrtoBST(arr,0,len(arr)-1)


你可能感兴趣的:(python,cc150)