Created
November 13, 2023 18:57
-
-
Save Mastermind-U/e01ac1e1960abe57cc912870190ffe3b to your computer and use it in GitHub Desktop.
Binary search tree, no recursion.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Python3 function to search a given key in a given BST.""" | |
class Node: | |
left: 'Node' = None | |
right: 'Node' = None | |
def __init__(self, key): | |
self.key = key | |
def insert(self, key): | |
if key == self.key: | |
raise ValueError | |
if key < self.key: | |
if self.left: | |
self.left.insert(key) | |
else: | |
self.left = Node(key) | |
elif key > self.key: | |
if self.right: | |
self.right.insert(key) | |
else: | |
self.right = Node(key) | |
return self | |
def search(self, key): | |
if self.key == key: | |
return self | |
if self.key < key: | |
if not self.right: | |
raise FileNotFoundError | |
return self.right.search(key) | |
if not self.left: | |
raise FileNotFoundError | |
return self.left.search(key) | |
if __name__ == '__main__': | |
root = Node(50) | |
root.insert(30) | |
root.insert(20) | |
root.insert(40) | |
root.insert(70) | |
root.insert(60) | |
root.insert(80) | |
# Key to be found | |
key = 6 | |
# Searching in a BST | |
if root.search(key) is None: | |
print(key, "not found") | |
else: | |
print(key, "found") | |
key = 60 | |
# Searching in a BST | |
if root.search(key) is None: | |
print(key, "not found") | |
else: | |
print(key, "found") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment