From ad5da75a273d29cc890cbe9ffe069c90ed166b9b Mon Sep 17 00:00:00 2001 From: xiomara Date: Tue, 17 Jan 2023 21:14:35 -0500 Subject: [PATCH] binary search tree exercise --- binary_search_trees/array_to_bst.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/binary_search_trees/array_to_bst.py b/binary_search_trees/array_to_bst.py index f69cc42..6d980cb 100644 --- a/binary_search_trees/array_to_bst.py +++ b/binary_search_trees/array_to_bst.py @@ -1,5 +1,5 @@ class TreeNode: - def __init__(self, value, left = None, right = None): + def __init__(self, value, left=None, right=None): self.val = value self.left = left self.right = right @@ -10,4 +10,16 @@ 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 + # base case: if the input array is empty, return None + if not arr: + return None + # Find the middle element of the array + mid = len(arr) // 2 + # Create a new TreeNode with the middle element as the value + root = TreeNode(arr[mid]) + # Recursively call the function for the left sub-array and assign the returned value as the left child of the root node + root.left = arr_to_bst(arr[:mid]) + # Recursively call the function for the right sub-array and assign the returned value as the right child of the root node + root.right = arr_to_bst(arr[mid+1:]) + # return the root of the balanced BST + return root