Skip to content

solution added #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion binary_search_trees/array_to_bst.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,21 @@ def arr_to_bst(arr):
Balanced Binary Search Tree using the elements in the array.
Return the root of the Binary Search Tree.
"""
pass
if arr == []:
return None

left = 0
right = len(arr) -1
return binary_search_in_arr(arr, left, right)


def binary_search_in_arr(arr, left, right):
if arr == []:
return None
if right >= left:
mid = left + (right - left) // 2
node = TreeNode(arr[mid])
node.right = binary_search_in_arr(arr, mid+1, right)
node.left = binary_search_in_arr(arr, left , mid - 1)
return node
return None
2 changes: 1 addition & 1 deletion tests/test_array_to_bst.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test_will_return_balanced_bst_for_even_lengthed_list():
answer = arr_to_bst(arr)

# Assert
assert is_bst(answer) and is_balanced_tree(answer)
assert is_bst(answer) and is_balanced_tree(answer)

def test_will_return_balanced_bst_for_long_list():
# Arrange
Expand Down