From 4bea3db8c786333512ee8296425878dd6f632ed9 Mon Sep 17 00:00:00 2001 From: Tetiana Zakipna Date: Thu, 13 Oct 2022 15:27:18 -0700 Subject: [PATCH] solution added --- binary_search_trees/array_to_bst.py | 19 ++++++++++++++++++- tests/test_array_to_bst.py | 2 +- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/binary_search_trees/array_to_bst.py b/binary_search_trees/array_to_bst.py index f69cc42..7c49f54 100644 --- a/binary_search_trees/array_to_bst.py +++ b/binary_search_trees/array_to_bst.py @@ -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 \ No newline at end of file + 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 \ No newline at end of file diff --git a/tests/test_array_to_bst.py b/tests/test_array_to_bst.py index 8246fe8..1fe4e10 100644 --- a/tests/test_array_to_bst.py +++ b/tests/test_array_to_bst.py @@ -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