Skip to content
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
completes binary_search_tree with breadth_first_for_each
  • Loading branch information
mattwright42 committed Mar 1, 2019
commit a8f76e9a7257a42f8fc73b991dbc0c389d33c7f3
94 changes: 54 additions & 40 deletions search/binary_search_tree.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,60 @@
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __init__(self, value):
self.value = value
self.left = None
self.right = None

def depth_first_for_each(self, cb):
pass
def depth_first_for_each(self, cb):
pass

def breadth_first_for_each(self, cb):
pass
def breadth_first_for_each(self, cb):
# initialize queue at self
bst_queue = [self]

def insert(self, value):
new_tree = BinarySearchTree(value)
if (value < self.value):
if not self.left:
self.left = new_tree
else:
self.left.insert(value)
elif value >= self.value:
if not self.right:
self.right = new_tree
else:
self.right.insert(value)
# loop through queue
while len(bst_queue):
# take the first element and put it in a variable
cur_node = bst_queue.pop(0)
# check to see if there is a left and add to bst_queue
if cur_node.left:
bst_queue.append(cur_node.left)
# check to see if there is a right and add to bst_queue
if cur_node.right:
bst_queue.append(cur_node.right)
# perform function on the current node
cb(cur_node.value)

def contains(self, target):
if self.value == target:
return True
if self.left:
if self.left.contains(target):
return True
if self.right:
if self.right.contains(target):
return True
return False
def insert(self, value):
new_tree = BinarySearchTree(value)
if (value < self.value):
if not self.left:
self.left = new_tree
else:
self.left.insert(value)
elif value >= self.value:
if not self.right:
self.right = new_tree
else:
self.right.insert(value)

def get_max(self):
if not self:
return None
max_value = self.value
current = self
while current:
if current.value > max_value:
max_value = current.value
current = current.right
return max_value
def contains(self, target):
if self.value == target:
return True
if self.left:
if self.left.contains(target):
return True
if self.right:
if self.right.contains(target):
return True
return False

def get_max(self):
if not self:
return None
max_value = self.value
current = self
while current:
if current.value > max_value:
max_value = current.value
current = current.right
return max_value