Skip to content

Instantly share code, notes, and snippets.

@onelharrison
Created May 25, 2020 08:02
Show Gist options
  • Save onelharrison/13d9e6955801dfc116538bf7d08bacc3 to your computer and use it in GitHub Desktop.
Save onelharrison/13d9e6955801dfc116538bf7d08bacc3 to your computer and use it in GitHub Desktop.
Leetcode: Convert Sorted Array to Binary Search Tree
class bst_node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
# assumes arr is sorted
def bst_from_array(arr):
if len(arr) == 0:
return None
mid = len(arr) // 2
root = bst_node(arr[mid])
root.right = bst_from_array(arr[mid + 1 :])
root.left = bst_from_array(arr[:mid])
return root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment