I am writing a code for splay tree but I have doubts regarding the deletion aspect of the splay tree. After researching about it on the internet, this is what I found:
First search the element to be deleted and splay it to the top.Then do the following
- If the root (after splaying the element to the top) has both left and right child, delete the root such that you have now two subtrees.In the left subtree, find the largest element and splay it to the top and then connect it the root of the right subtree.
- If the root has no left child but has a right child,then delete the root and make the root of the right subtree as the new root.
But what happens if the root has no right child? So I delete the root and make the root of the left subtree as the new root?
Are there any other conditions that I need to take care of?
If it helps, I have written the deletion code below.
def delete(self,key):
res = self.get(key) #The get() function also does the splaying operation as well
if res:
ls = self.root.leftChild
rs = self.root.rightChild
if ls is not None and rs is not None: #has both the child
ls.parent = None
rs.parent = None
current = ls
while ls.hasRightChild():
current = current.rightChild #find the largest element
self.get(current.key)
rs.parent = current
current.rightChild = rs
self.root = current
elif ls is None and rs is not None: #has no left child
rs.parent = None
self.root = rs
elif ls is None and rs is None: #has no left or right child ie the tree contains only one node
self.root = None
else:
return