BST Remove method implementation in Python











up vote
-2
down vote

favorite












class BSTNode:
"""
Represents nodes in a binary search tree.
"""
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None

def height(self):
"""Return the height of this node."""
left_height = 1 + self.left.height() if self.left else 0
right_height = 1 + self.right.height() if self.right else 0
return max(left_height, right_height)

def __repr__(self):
return "<BSTNode: key={!r}, value={!r}, id={}>".format(self.key, self.value, id(self))



class BSTException(Exception):
pass


class BST:
"""
Simple recursive binary search tree implementation.
"""
def __init__(self, NodeClass=BSTNode):
self.BSTNode = NodeClass
self.root = None
self.nodes = 0
# Updated after each call to insert
self.newest_node = None

def find(self, find_key):
"""Return node with key find_key if it exists. If not, return None. """
return self._findhelp(self.root, find_key)

def insert(self, new_key, value=None):
"""Insert a new node with key new_key into this BST,
increase node count by one and return the inserted node."""
if self.find(new_key) is not None:
raise KeyError("This BST already contains key {0!r}".format(new_key))
self.root = self._inserthelp(self.root, new_key, value)
self.nodes += 1
return self.newest_node

def height(self):
"""Return the height of this tree."""
return self.root.height() if self.root else -1

def __iter__(self):
"""Return an iterator of the keys of this tree in sorted order."""
for node in self._visit_inorder(self.root):
yield node.key

def __len__(self):
return self.nodes



def remove(self, key):
temp=self.find(key)
if temp != None:
self.root = self.removehelp(self.root, key)
self.nodes-=1
return temp


def removehelp(self, node, key):
if node==None:
return None
if node.key > key:
node.left=self.removehelp(node.left, key)
elif node.key < key:
node.right=self.removehelp(node.right, key)
else:
if node.left==None:
return node.right
elif node.right == None:
return node.left
else:
temp=BSTNode(self.findmax(node.left).key)
node.key=temp.key
node.left=self.removemax(node.left)
return node


def removemax(self,node):
if node.right==None:
return node.left
node.right=self.removemax(node.right)
return node


def findmax(self, node):
if node.right==None:
return node
return self.findmax(node.right)


def _findhelp(self, node, find_key):
if node == None or find_key==node.key:
return node
elif node.key > find_key:
return self._findhelp(node.left, find_key)
else:
return self._findhelp(node.right, find_key)


def _inserthelp(self, node, new_key, value):
if node is None:
self.newest_node = self.BSTNode(new_key, value)
return self.newest_node
if node.key >= new_key:
node.left=self._inserthelp(node.left, new_key, value)
else:
node.right=self._inserthelp(node.right, new_key, value)
return node


I would need help in implementing remove method and its helper methods removehelp, removemax and findmax in BST class.



The remove method accepts as a parameter one integer, which is the key of the node to be removed. If a node with the given parameter key exists, the node is removed from the tree, the node counter is decremented and the node is returned. Else, nothing happens and None is returned



This should be basic stuff, but for some reason I don't get it right. Any assistance is greatly appreciated!










share|improve this question







New contributor




Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    Welcome to codereview. This site is for reviews of already working code, not asking for help about how to right new code.
    – Oscar Smith
    4 hours ago















up vote
-2
down vote

favorite












class BSTNode:
"""
Represents nodes in a binary search tree.
"""
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None

def height(self):
"""Return the height of this node."""
left_height = 1 + self.left.height() if self.left else 0
right_height = 1 + self.right.height() if self.right else 0
return max(left_height, right_height)

def __repr__(self):
return "<BSTNode: key={!r}, value={!r}, id={}>".format(self.key, self.value, id(self))



class BSTException(Exception):
pass


class BST:
"""
Simple recursive binary search tree implementation.
"""
def __init__(self, NodeClass=BSTNode):
self.BSTNode = NodeClass
self.root = None
self.nodes = 0
# Updated after each call to insert
self.newest_node = None

def find(self, find_key):
"""Return node with key find_key if it exists. If not, return None. """
return self._findhelp(self.root, find_key)

def insert(self, new_key, value=None):
"""Insert a new node with key new_key into this BST,
increase node count by one and return the inserted node."""
if self.find(new_key) is not None:
raise KeyError("This BST already contains key {0!r}".format(new_key))
self.root = self._inserthelp(self.root, new_key, value)
self.nodes += 1
return self.newest_node

def height(self):
"""Return the height of this tree."""
return self.root.height() if self.root else -1

def __iter__(self):
"""Return an iterator of the keys of this tree in sorted order."""
for node in self._visit_inorder(self.root):
yield node.key

def __len__(self):
return self.nodes



def remove(self, key):
temp=self.find(key)
if temp != None:
self.root = self.removehelp(self.root, key)
self.nodes-=1
return temp


def removehelp(self, node, key):
if node==None:
return None
if node.key > key:
node.left=self.removehelp(node.left, key)
elif node.key < key:
node.right=self.removehelp(node.right, key)
else:
if node.left==None:
return node.right
elif node.right == None:
return node.left
else:
temp=BSTNode(self.findmax(node.left).key)
node.key=temp.key
node.left=self.removemax(node.left)
return node


def removemax(self,node):
if node.right==None:
return node.left
node.right=self.removemax(node.right)
return node


def findmax(self, node):
if node.right==None:
return node
return self.findmax(node.right)


def _findhelp(self, node, find_key):
if node == None or find_key==node.key:
return node
elif node.key > find_key:
return self._findhelp(node.left, find_key)
else:
return self._findhelp(node.right, find_key)


def _inserthelp(self, node, new_key, value):
if node is None:
self.newest_node = self.BSTNode(new_key, value)
return self.newest_node
if node.key >= new_key:
node.left=self._inserthelp(node.left, new_key, value)
else:
node.right=self._inserthelp(node.right, new_key, value)
return node


I would need help in implementing remove method and its helper methods removehelp, removemax and findmax in BST class.



The remove method accepts as a parameter one integer, which is the key of the node to be removed. If a node with the given parameter key exists, the node is removed from the tree, the node counter is decremented and the node is returned. Else, nothing happens and None is returned



This should be basic stuff, but for some reason I don't get it right. Any assistance is greatly appreciated!










share|improve this question







New contributor




Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    Welcome to codereview. This site is for reviews of already working code, not asking for help about how to right new code.
    – Oscar Smith
    4 hours ago













up vote
-2
down vote

favorite









up vote
-2
down vote

favorite











class BSTNode:
"""
Represents nodes in a binary search tree.
"""
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None

def height(self):
"""Return the height of this node."""
left_height = 1 + self.left.height() if self.left else 0
right_height = 1 + self.right.height() if self.right else 0
return max(left_height, right_height)

def __repr__(self):
return "<BSTNode: key={!r}, value={!r}, id={}>".format(self.key, self.value, id(self))



class BSTException(Exception):
pass


class BST:
"""
Simple recursive binary search tree implementation.
"""
def __init__(self, NodeClass=BSTNode):
self.BSTNode = NodeClass
self.root = None
self.nodes = 0
# Updated after each call to insert
self.newest_node = None

def find(self, find_key):
"""Return node with key find_key if it exists. If not, return None. """
return self._findhelp(self.root, find_key)

def insert(self, new_key, value=None):
"""Insert a new node with key new_key into this BST,
increase node count by one and return the inserted node."""
if self.find(new_key) is not None:
raise KeyError("This BST already contains key {0!r}".format(new_key))
self.root = self._inserthelp(self.root, new_key, value)
self.nodes += 1
return self.newest_node

def height(self):
"""Return the height of this tree."""
return self.root.height() if self.root else -1

def __iter__(self):
"""Return an iterator of the keys of this tree in sorted order."""
for node in self._visit_inorder(self.root):
yield node.key

def __len__(self):
return self.nodes



def remove(self, key):
temp=self.find(key)
if temp != None:
self.root = self.removehelp(self.root, key)
self.nodes-=1
return temp


def removehelp(self, node, key):
if node==None:
return None
if node.key > key:
node.left=self.removehelp(node.left, key)
elif node.key < key:
node.right=self.removehelp(node.right, key)
else:
if node.left==None:
return node.right
elif node.right == None:
return node.left
else:
temp=BSTNode(self.findmax(node.left).key)
node.key=temp.key
node.left=self.removemax(node.left)
return node


def removemax(self,node):
if node.right==None:
return node.left
node.right=self.removemax(node.right)
return node


def findmax(self, node):
if node.right==None:
return node
return self.findmax(node.right)


def _findhelp(self, node, find_key):
if node == None or find_key==node.key:
return node
elif node.key > find_key:
return self._findhelp(node.left, find_key)
else:
return self._findhelp(node.right, find_key)


def _inserthelp(self, node, new_key, value):
if node is None:
self.newest_node = self.BSTNode(new_key, value)
return self.newest_node
if node.key >= new_key:
node.left=self._inserthelp(node.left, new_key, value)
else:
node.right=self._inserthelp(node.right, new_key, value)
return node


I would need help in implementing remove method and its helper methods removehelp, removemax and findmax in BST class.



The remove method accepts as a parameter one integer, which is the key of the node to be removed. If a node with the given parameter key exists, the node is removed from the tree, the node counter is decremented and the node is returned. Else, nothing happens and None is returned



This should be basic stuff, but for some reason I don't get it right. Any assistance is greatly appreciated!










share|improve this question







New contributor




Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











class BSTNode:
"""
Represents nodes in a binary search tree.
"""
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None

def height(self):
"""Return the height of this node."""
left_height = 1 + self.left.height() if self.left else 0
right_height = 1 + self.right.height() if self.right else 0
return max(left_height, right_height)

def __repr__(self):
return "<BSTNode: key={!r}, value={!r}, id={}>".format(self.key, self.value, id(self))



class BSTException(Exception):
pass


class BST:
"""
Simple recursive binary search tree implementation.
"""
def __init__(self, NodeClass=BSTNode):
self.BSTNode = NodeClass
self.root = None
self.nodes = 0
# Updated after each call to insert
self.newest_node = None

def find(self, find_key):
"""Return node with key find_key if it exists. If not, return None. """
return self._findhelp(self.root, find_key)

def insert(self, new_key, value=None):
"""Insert a new node with key new_key into this BST,
increase node count by one and return the inserted node."""
if self.find(new_key) is not None:
raise KeyError("This BST already contains key {0!r}".format(new_key))
self.root = self._inserthelp(self.root, new_key, value)
self.nodes += 1
return self.newest_node

def height(self):
"""Return the height of this tree."""
return self.root.height() if self.root else -1

def __iter__(self):
"""Return an iterator of the keys of this tree in sorted order."""
for node in self._visit_inorder(self.root):
yield node.key

def __len__(self):
return self.nodes



def remove(self, key):
temp=self.find(key)
if temp != None:
self.root = self.removehelp(self.root, key)
self.nodes-=1
return temp


def removehelp(self, node, key):
if node==None:
return None
if node.key > key:
node.left=self.removehelp(node.left, key)
elif node.key < key:
node.right=self.removehelp(node.right, key)
else:
if node.left==None:
return node.right
elif node.right == None:
return node.left
else:
temp=BSTNode(self.findmax(node.left).key)
node.key=temp.key
node.left=self.removemax(node.left)
return node


def removemax(self,node):
if node.right==None:
return node.left
node.right=self.removemax(node.right)
return node


def findmax(self, node):
if node.right==None:
return node
return self.findmax(node.right)


def _findhelp(self, node, find_key):
if node == None or find_key==node.key:
return node
elif node.key > find_key:
return self._findhelp(node.left, find_key)
else:
return self._findhelp(node.right, find_key)


def _inserthelp(self, node, new_key, value):
if node is None:
self.newest_node = self.BSTNode(new_key, value)
return self.newest_node
if node.key >= new_key:
node.left=self._inserthelp(node.left, new_key, value)
else:
node.right=self._inserthelp(node.right, new_key, value)
return node


I would need help in implementing remove method and its helper methods removehelp, removemax and findmax in BST class.



The remove method accepts as a parameter one integer, which is the key of the node to be removed. If a node with the given parameter key exists, the node is removed from the tree, the node counter is decremented and the node is returned. Else, nothing happens and None is returned



This should be basic stuff, but for some reason I don't get it right. Any assistance is greatly appreciated!







python binary-search






share|improve this question







New contributor




Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 5 hours ago









Miro Lammi

1




1




New contributor




Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Miro Lammi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    Welcome to codereview. This site is for reviews of already working code, not asking for help about how to right new code.
    – Oscar Smith
    4 hours ago














  • 1




    Welcome to codereview. This site is for reviews of already working code, not asking for help about how to right new code.
    – Oscar Smith
    4 hours ago








1




1




Welcome to codereview. This site is for reviews of already working code, not asking for help about how to right new code.
– Oscar Smith
4 hours ago




Welcome to codereview. This site is for reviews of already working code, not asking for help about how to right new code.
– Oscar Smith
4 hours ago















active

oldest

votes











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Miro Lammi is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209315%2fbst-remove-method-implementation-in-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes








Miro Lammi is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















Miro Lammi is a new contributor. Be nice, and check out our Code of Conduct.













Miro Lammi is a new contributor. Be nice, and check out our Code of Conduct.












Miro Lammi is a new contributor. Be nice, and check out our Code of Conduct.
















Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209315%2fbst-remove-method-implementation-in-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Morgemoulin

Scott Moir

Souastre