Skip to content

Andrea Garcia C17 #6

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 3 commits 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
9 changes: 8 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,11 @@ def arr_to_bst(arr):
Balanced Binary Search Tree using the elements in the array.
Return the root of the Binary Search Tree.
"""
pass
while arr:
medi = (len(arr)) // 2
root = TreeNode(arr[medi])
root.left = arr_to_bst(arr[:medi])
root.right = arr_to_bst(arr[medi+1:])
return root
else:
return None
20 changes: 17 additions & 3 deletions tests/test_array_to_bst.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def test_will_return_balanced_bst_for_odd_lengthed_list():
answer = arr_to_bst(arr)

# Assert
assert answer.val is 25 and is_bst(answer) and is_balanced_tree(answer)
assert answer.val is 25 and is_bst(answer) and is_balanced_tree(answer) and inorder(answer) == arr

def test_will_return_balanced_bst_for_even_lengthed_list():
# Arrange
Expand All @@ -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) and inorder(answer) == arr

def test_will_return_balanced_bst_for_long_list():
# Arrange
Expand All @@ -34,7 +34,7 @@ def test_will_return_balanced_bst_for_long_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) and inorder(answer) == arr

def test_will_return_none_for_empty_list():
# Arrange
Expand Down Expand Up @@ -93,3 +93,17 @@ def is_balanced_tree(root):
right_check = is_balanced_tree(root.right)

return left_check and right_check

def inorder_helper(node, values):
if not node:
return values

inorder_helper(node.left, values)
values.append(node.val)
inorder_helper(node.right, values)

return values

def inorder(node):
values = []
return inorder_helper(node, values)