Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, cargo = None, left = None, right = None):
- self.cargo = cargo
- self.left = left
- self.right = right
- def __str__(self):
- return str(self.cargo)
- class BinarySearchTree:
- def __init__(self, root = None):
- self.root = root
- def insert(self, val):
- #if there is no root, create a Node at the root
- if self.root == None:
- self.root = Node(val)
- #if there is a root, check whether the value is greater than or less than the root
- #Check the appropriate left or right pointer to see if a Node exists, and continue evaluating
- #or assign to the left or right pointer when appropriate
- #else call Insert_Helper
- else:
- self.Insert_Helper(self.root, val)
- def Insert_Helper(self, current_node, val):
- #If the value is less than the current node's cargo
- if val < current_node.cargo:
- #if the current node's left is None
- if current_node.left == None:
- current_node.left = Node(val)
- else:
- self.Insert_Helper(current_node.left, val)
- elif val > current_node.cargo:
- #if the current node's right is None
- if current_node.right == None:
- #Create a node with that value
- current_node.right = Node(val)
- else:
- self.Insert_Helper(current_node.right, val)
- def search(self, val):
- search_t1 = perf_counter()
- result = self.search_helper(self.root, val)
- if result:
- search_t2 = perf_counter()
- time_elapsed = search_t2 - search_t1
- print('Elapsed time: ' + str(time_elapsed))
- return True
- else:
- search_t2 = perf_counter()
- time_elapsed = search_t2 - search_t1
- print('Elapsed time: ' + str(time_elapsed))
- return False
- def search_helper(self, current_node, val):
- #if the current node is empty, return False
- if current_node == None:
- return False
- #elif the current node is the value, return True
- elif current_node.cargo == val:
- return True
- elif val < current_node.cargo:
- self.search_helper(current_node.left, val)
- elif val > current_node.cargo:
- self.search_helper(current_node.right, val)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement