I’m struggling getting my Delete function to work for my BST class, I mostly understand the idea behind but can’t quite get the implementation right.
Here in DataStructures.py I have a class for the BST, it pulls from another class DataStructures which just takes in a list of arguments for values.
# Class for Binary Search Tree (BST)
class BST(DataStructures):
def __init__(self, *args):
self.root = None
for arg in args:
self.insert(arg)
# Function to insert into tree
def insert(self, data):
new_node = self.BSTNode(data)
if self.root is None:
self.root = new_node
else:
current_node = self.root
while current_node != None:
if current_node.data < new_node.data:
if current_node.right is None:
current_node.right = new_node
return
else:
current_node = current_node.right
elif current_node.data > new_node.data:
if current_node.left is None:
current_node.left = new_node
return
else:
current_node = current_node.left
# Function to search BST
def search(self, value):
node = self.root
count = 1
if node is None:
print("Tree is Empty")
elif value == node.data:
print(f"{value} in line {count} of tree.")
else:
while node != None and node.data != value:
count +=1
if node.data < value:
node = node.right
elif node.data > value:
node = node.left
if node is None:
print(f"{value} Not in Tree")
else:
print(f"{value} in line {count} of tree.")
# Function to get min value in BST
def getMin(self, node = "root"):
if node == "root":
node = self.root
min = node.data
while node.left != None:
min = node.left.data
node = node.left
return min
# Function to get max value in BST
def getMax(self, node = "root"):
if node == "root":
node = self.root
max = node.data
while node.right != None:
max = node.right.data
node = node.right
return max
# Function to delete a node in BST
def delNode(self, value, node = "root"):
if node == "root":
node = self.root
if node is None:
return node
if value < node.data:
node.left = self.delNode(value, node.left)
elif value > node.data:
node.right = self.delNode(value, node.right)
else:
if node.left is None:
return node.right
elif node.right is None:
return node.left
node.data = self.getMin(node.right)
node.right = self.delNode(node.data, node.right)
return node
# Function to traverse in-order BST
def inOrder(self, node = "root"):
if node == "root":
node = self.root
if node: # Recursively print left-right most nodes on tree
self.inOrder(node.left)
print(node.data, end=" ")
self.inOrder(node.right)
# Function to get BST height
def getHeight(self, node = "root"):
if node == "root":
node = self.root
if node is None:
return 0
leftHeight = self.getHeight(node.left) # Recursively get height of left/right nodes then return the larger
rightHeight = self.getHeight(node.right) # of them, adding 1 to their increment each time,
return max(leftHeight, rightHeight) + 1
# Function to see if BST is balanced
def getBalance(self, node = "root"):
if node == "root":
node = self.root
if node is None:
return True
left_height = self.getHeight(node.left) # Get height from either side of our root node
right_height = self.getHeight(node.right)
if((left_height - right_height) > 1 or (left_height - right_height) < -1):
return False
left_balance = self.getBalance(node.left) # Check if each subtree is balanced, return True if so
right_balance = self.getBalance(node.right)
if left_balance == True and right_balance == True:
return True
# String Method for BST see repr function in BSTNode Class
def __str__(self) -> str:
if self.root is None:
return "Tree is Empty"
else:
return repr(self)
def __repr__(self):
return repr(self.root)
# Class for Nodes of the BST
class BSTNode():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Return String Representation of BST (taken from /a/62407035)
def __repr__(self):
lines = []
if self.right:
found = False
for line in repr(self.right).split("n"):
if line[0] != " ":
found = True
line = " ┌─" + line
elif found:
line = " | " + line
else:
line = " " + line
lines.append(line)
lines.append(str(self.data))
if self.left:
found = False
for line in repr(self.left).split("n"):
if line[0] != " ":
found = True
line = " └─" + line
elif found:
line = " " + line
else:
line = " | " + line
lines.append(line)
return "n".join(lines)
And here is my main.py with various tests while I coded the BST
import DataStructures
bst = DataStructures.BST(4, 2, 6, 3, 1, 5, 8, 10)
# bst.insert(10)
# bst.insert(5)
# bst.search(0)
# print(bst.getMax())
# bst.inOrder()
# print(bst.getHeight())
# print(bst.getBalance())
# print(bst)
bst.delNode(8)
print(bst)
bst.inOrder()
After trying for a while myself and getting nowhere I attempted implementing code from other stackoverflow questions and various other outlets but couldn’t get it to overwrite the correct node. In my main.py example only the 8 node should be removed but I always end up with all of the right tree deleted
Output from main.py:
4
| ┌─3
└─2
└─1
1 2 3 4
Nicholas Hodder is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.