25
loading...
This website collects cookies to deliver better user experience
20
/ \
12 23
/ \ / \
7 15 21 35
20
/ \
12 23
/ \ / \
7 15 21 35
\
17
root = root. right
root = root. left
previousRoot = None
if the binary search tree is empty. so the previousRoot will be the new Node previousRoot = Node(elementToInsert)
previousRoot < elementToInsert
if the previousRoot is less than the elementToInsert, so the node will be the right child of the previousRoot previousRoot.right = elementToInsert
previousRoot >= elementToInsert
if the previousRoot is greater than or equal the elementToInsert, so the node will be the left child of the previousRoot previousRoot.left = elementToInsert
def insert(elementToInsert: int, root = None):
# new node
TheNewNode = Node(elementToInsert)
previousRoot = None
while root is not None:
previousRoot = root
# if the root's value is less than elementToInsert
if root.value < elementToInsert:
# the root variable will be the root of the right sub-tree
root = root.right
# if the root value is greater than or equal elementToInsert
else:
# the root variable will be the root of the left sub-tree
root = root.left
# if the binary search tree is empty
if previousRoot is None:
previousRoot = TheNewNode
# if the previous root value is greater than or equal the elementToInsert
elif previousRoot.value >= elementToInsert:
# the new node will be its left child
previousRoot.left = TheNewNode
# if the previous root value is less than the elementToInsert
else:
# the new node will be its right child
previousRoot.right = TheNewNode
return TheNewNode
20
/ \
12 23
/ \ / \
7 15 21 35
# If there are no more nodes.
# that means the node value will be None(null)
# that means the wanted element doesn't exist
if root == None:
# the wanted element is not found so return False
return False
# if the root value is equal to the wanted element
# that means the wanted element is found
if root.value == wantedElement:
# return the node
return root
# if the root value is smaller than the wanted element
if root.value < wantedElement:
# return the same function with the root of the right sub-tree
return search( wantedElement, root.right)
# if the root value is greater than or equal the wanted element
if root.value >= wantedElement:
# return the same function with the root of the left sub-tree
return search( wantedElement, root.left)