delete node in binary search tree python

2024/9/8 10:59:07

The code below is my implement for my binary search tree, and I want to implement delete method to remove the node. Below is my implementation, but when I perform

bst = BSTRee()
bst.insert(5)
bst.insert(11)
bst.insert(3)
bst.insert(4)
bst.insert(12)
bst.insert(2)
bst.delete(3)

when I call delete method, it did nothing. Can someone help me to fix it. The link below is my code on github. Thank you so much for your help. https://github.com/hly189/sort/blob/master/tree/BST.py

class BSTreeNodedef ____init__(self, value): self.value = value self.left = None self.right = Nonedef insert(self,key): if self.value == key: print ("the node already exists")return False elif self.value > key: if self.left is not None: return self.left.insert(key)else: self.left = BSTreeNode(key)return Trueelse: if self.right is not None: return self.right.insert(key)else: self.right = BSTreeNode(key)return Falsedef delete(self, node, k):if node == None: return Noneelif node.value == k: if node.left is None and node.right is None: return Noneelif node.left is None: return node.rightelif node.right is None: return node.left else: node.value = get_min(node.right)node.right.delete(node.right,node.value)elif k < node.value: node.left.delete(node.left,k)else: node.right.delete(node.right,k)return nodeclass BSTree: def __init__(self): self.root = None def delete(self,key): self.root.delete(self.root,key)def insert(self,data): if self.root: self.root.insert(data)else: self.root = BSTreeNode(data)return True def find_min(self,node):current_node = nodewhile current_node.left: current_node = current_node.leftreturn current_nodedef get_min(node): current_node = nodewhile current_node.left: current_node = current_node.leftreturn str(current_node.value)def print_helper(root, indent):if root is not None:print_helper(root.right, indent + "   ")print (indent + str(root.value))print_helper(root.left, indent + "   ")def print_tree(root):print_helper(root, "")
Answer
def delete(self, key):""" delete the node with the given key and return the root node of the tree """if self.key == key:# found the node we need to deleteif self.right and self.left: # get the successor node and its parent [psucc, succ] = self.right._findMin(self)# splice out the successor# (we need the parent to do this) if psucc.left == succ:psucc.left = succ.rightelse:psucc.right = succ.right# reset the left and right children of the successorsucc.left = self.leftsucc.right = self.rightreturn succ                else:# "easier" caseif self.left:return self.left    # promote the left subtreeelse:return self.right   # promote the right subtree else:if self.key > key:          # key should be in the left subtreeif self.left:self.left = self.left.delete(key)# else the key is not in the tree else:                       # key should be in the right subtreeif self.right:self.right = self.right.delete(key)return selfdef _findMin(self, parent):""" return the minimum node in the current tree and its parent """# we use an ugly trick: the parent node is passed in as an argument# so that eventually when the leftmost child is reached, the # call can return both the parent to the successor and the successorif self.left:return self.left._findMin(self)else:return [parent, self]

This might help. For complete code and better understanding go to For code Binary search Tree in Python

For explanation Notes on BST in Python As per my knowledge its working fine.

https://en.xdnf.cn/q/72597.html

Related Q&A

ImportError: cannot import name cbook when using PyCharms Profiler

I am trying to run the PyCharm profiler but I get the following error message:Traceback (most recent call last):File "/home/b3053674/ProgramFiles/pycharm-2017.1.4/helpers/profiler/run_profiler.py&…

Replicating SAS first and last functionality with Python

I have recently migrated to Python as my primary tool for analysis and I am looking to be able to replicate the first. & last. functionality found in SAS. The SAS code would be as follows;data data…

Can mypy track string literals?

Is there anyway to make this work from typing import Literal def foo(bar: Literal["bar"]) -> Literal["foo"]:foo = "foo"return foobar = "bar" foo(bar)Here are …

Lazy loading of attributes

How would you implement lazy load of object attributes, i.e. if attributes are accessed but dont exist yet, some object method is called which is supposed to load these?My first attempt isdef lazyload…

Using pythons property while loading old objects

I have a rather large project, including a class Foo which recently needed to be updated using the @property decorator to create custom getter and setter methods.I also stored several instances of Foo …

How to replace all those Special Characters with white spaces in python?

How to replace all those special characters with white spaces in python ?I have a list of names of a company . . . Ex:-[myfiles.txt] MY company.INCOld Wine pvtmaster-minds ltd"apex-labs ltd"…

Python 3.x : move to next line

Ive got a small script that is extracting some text from a .html file.f = open(local_file,"r") for line in f:searchphrase = <span class="positionif searchphrase in line:print("fo…

Why couldnt Julia superset python?

The Julia Language syntax looks very similar to python, while the concept of a class (if one should address it as such a thing) is more what you use in C. There were many reasons why the creators decid…

How to log into Google Cloud Storage from a python function?

I am new to google cloud storage and I try to set up a function that downloads a blob once a day. At the moment I am working in my Jupyter Notebook but finally, the code will run in an Azure Function. …

OpenCV Python, reading video from named pipe

I am trying to achieve results as shown on the video (Method 3 using netcat)https://www.youtube.com/watch?v=sYGdge3T30oThe point is to stream video from raspberry pi to ubuntu PC and process it using …