mirror of
https://github.com/jlengrand/Coding4Interviews.git
synced 2026-03-10 08:11:24 +00:00
Add method added. Also adds convenience method has_child in node class
This commit is contained in:
@@ -15,6 +15,31 @@ class BinarySearchTree():
|
||||
self.size = 0
|
||||
self.root_node = None
|
||||
|
||||
def add(self, value):
|
||||
if self.size == 0:
|
||||
self.root_node = BinarySearchNode(value, None) # root node has no parent
|
||||
|
||||
else:
|
||||
node = self.root_node
|
||||
is_left = None
|
||||
while(node != None):
|
||||
ptr_node = node # keep parent in memory
|
||||
if node.value > value: # we go to the left child
|
||||
node = node.left_child
|
||||
is_left = True
|
||||
else: # we move to the right child
|
||||
node = node.right_child
|
||||
is_left = False
|
||||
|
||||
# we achieved a leaf
|
||||
node = BinarySearchNode(value, ptr_node)
|
||||
if is_left:
|
||||
ptr_node.left_child = node
|
||||
else:
|
||||
ptr_node.right_child = node
|
||||
|
||||
self.size += 1
|
||||
|
||||
class BinarySearchNode():
|
||||
"""
|
||||
Defines any node of the Binary Search Tree.
|
||||
@@ -22,8 +47,15 @@ class BinarySearchNode():
|
||||
It also must have a parent
|
||||
"""
|
||||
def __init__(self, value, parent):
|
||||
self.parent_node = parent
|
||||
self.node_value = value
|
||||
self.parent = parent
|
||||
self.value = value
|
||||
|
||||
self.left_child = None
|
||||
self.right_child = None
|
||||
|
||||
def has_left_child(self):
|
||||
return not(self.left_child is None)
|
||||
|
||||
def has_right_child(self):
|
||||
return self.right_child is not None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user