Skip to content

Xiomara Rodriguez cs-fun-a #96

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
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
16 changes: 14 additions & 2 deletions binary_search_trees/array_to_bst.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
# 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