I'm working on a binary search tree class and we have to implement the remove method using recursion. Here is the code that was given to us.
def remove (self, x):
def recurse (p):
# Modify this method.
if p==None:
return p
elif x<p.data:
return p
elif x>p.data:
return p
elif p.left==None and p.right==None: # case (1)
return p
elif p.right==None: # case (2)
return p
elif p.left==None: # case (3)
return p
else: # case (4)
return p
self.root = recurse (self.root)
Obviously there should be more than just return p for each conditional. And I'm pretty sure the first if and two elifs are used to 'locate' the node containing x. However I am not sure how to implement the four cases. Any input would be appreciated.
Also, the end goal is to use this method to iterate through the BST and remove each node.
-
1what is one requirement of recursion? it needs to _______, and must have at least one ___________.Joran Beasley– Joran Beasley2015年04月09日 23:12:27 +00:00Commented Apr 9, 2015 at 23:12
2 Answers 2
Well, your first step is to locate X, remember that you do this by recursion, so you should recurse the remove function on the child tree its located. (left if x < p.data, right if higher... only if they exist). Next, you need to worry what to do once you find x (x = p.data).
I would recommend drawing a tree and think as an algorithm. :)
Remember the BST property! The tree will necesarily modify it's structure to preserve the property, so.. who is the new father of the lonely childs? hints:
a sibling possibly?
.
remember the BST charasteristic
.
recursion!!!)
4 Comments
pseudo_code method_recurse requires argument: this_node
- if this_node is None then return None Found
- if this_node is target then return this_node
- if this_node is less_than target then return call self with this_node.right
- if this_node is greater_than target then return call self with this_node.left
Comments
Explore related questions
See similar questions with these tags.