From fede92ff3d22d3c7c1496d5ce2d2372db831e9b7 Mon Sep 17 00:00:00 2001 From: Ivana Maldonado Date: Fri, 20 Jan 2023 14:14:22 -0500 Subject: [PATCH] Recusrive solution. All tests passed. --- binary_search_trees/array_to_bst.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/binary_search_trees/array_to_bst.py b/binary_search_trees/array_to_bst.py index f69cc42..070539b 100644 --- a/binary_search_trees/array_to_bst.py +++ b/binary_search_trees/array_to_bst.py @@ -10,4 +10,19 @@ 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 not arr: + return None + + # Recusive approach: + # Find the middle index of the array + mid = len(arr) // 2 + + # Create a new root node with the value of mid + root = TreeNode(arr[mid]) + + # Left subtree has all the elements less than mid + root.left = arr_to_bst(arr[:mid]) + # Right subtree has all the elements to greater or equal to mid + root.right = arr_to_bst(arr[mid + 1:]) + + return root