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
binarysearch tree
  • Loading branch information
bykristea committed Jan 11, 2020
commit fac3291b138873dd5353fe03788c937a3eb7b964
59 changes: 59 additions & 0 deletions names/names_bst.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
class BinarySearchTree:
def __init__(self, value): # just using value. key is value
self.value = value
self.left = None
self.right = None
self.root = None

# Insert the given value into the tree
# need to traverse to find spot to insert
def insert(self, value):
if value < self.value:
if not self.left:
self.left = BinarySearchTree(value)
else:
self.left.insert(value)

# if value >= self.value:
else:
if not self.right:
self.right = BinarySearchTree(value)
else:
self.right.insert(value)

# Return True if the tree contains the value
# False if it does not
# start from root and traverse the tree. we can stop at the first instance of a value. we know its not found if we get to a node that does not have children

def contains(self, target):
if target == self.value:
return True
if target < self.value:
if not self.left:
return False
else:
return self.left.contains(target)

else:
if self.right is None:
return False
else:
return self.right.contains(target)

# Return the maximum value found in the tree

def get_max(self):
if self.right:
return self.right.get_max()
else:
return self.value

# Call the function `cb` on the value of each node
# You may use a recursive or iterative approach
#
def for_each(self, cb):
cb(self.value)
if self.left:
self.left.for_each(cb)
if self.right:
self.right.for_each(cb)