Skip to content

Added doctest to binary_search_tree.py #11144

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

Closed
wants to merge 1 commit into from
Closed
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
42 changes: 42 additions & 0 deletions data_structures/binary_tree/binary_search_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,30 @@ def insert(self, *values) -> Self:
return self

def search(self, value) -> Node | None:
"""
>>> bst = BinarySearchTree().insert(10,20,30,40,50)
>>> bst.search(10)
{'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})}
>>> bst.search(20)
{'20': (None, {'30': (None, {'40': (None, 50)})})}
>>> bst.search(30)
{'30': (None, {'40': (None, 50)})}
>>> bst.search(40)
{'40': (None, 50)}
>>> bst.search(50)
50
>>> bst.search(0) # element not present

>>> bst.search(-5 ) # element not present

>>> bst.search(5) # element not present

>>> bst= BinarySearchTree().search(10)
Traceback (most recent call last):
...
IndexError: Warning: Tree is empty! please use another.
"""

if self.empty():
raise IndexError("Warning: Tree is empty! please use another.")
else:
Expand All @@ -210,6 +234,15 @@ def search(self, value) -> Node | None:
def get_max(self, node: Node | None = None) -> Node | None:
"""
We go deep on the right branch

>>> BinarySearchTree().insert(10,20,30,40,50).get_max()
50
>>> BinarySearchTree().insert(-5,-1,0,-0.3,-4.5).get_max()
{'0': (-0.3, None)}
>>> BinarySearchTree().insert(1,78.3,30,74.0,1).get_max()
{'78.3': ({'30': (1, 74.0)}, None)}
>>> BinarySearchTree().insert(1,783,30,740,1).get_max()
{'783': ({'30': (1, 740)}, None)}
"""
if node is None:
if self.root is None:
Expand All @@ -224,6 +257,15 @@ def get_max(self, node: Node | None = None) -> Node | None:
def get_min(self, node: Node | None = None) -> Node | None:
"""
We go deep on the left branch

>>> BinarySearchTree().insert(10,20,30,40,50).get_min()
{'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})}
>>> BinarySearchTree().insert(-5,-1,0,-0.3,-4.5).get_min()
{'-5': (None, {'-1': (-4.5, {'0': (-0.3, None)})})}
>>> BinarySearchTree().insert(1,78.3,30,74.0,1).get_min()
{'1': (None, {'78.3': ({'30': (1, 74.0)}, None)})}
>>> BinarySearchTree().insert(1,783,30,740,1).get_min()
{'1': (None, {'783': ({'30': (1, 740)}, None)})}
"""
if node is None:
node = self.root
Expand Down