I am having touble with this method. It is a recursive method that deletes an el
ID: 3627859 • Letter: I
Question
I am having touble with this method. It is a recursive method that deletes an element from an BST. However when i do my output and it's like it's added more elements to the BST, and i have get and set methods that i utilize:
private TN delete(TN temp, E value)
{
if (temp!=null)
{
if(value.compareTo(temp.getData())>0)
{
temp.setRightNode(delete(temp.getRightNode(),value));
}
else if(value.compareTo(temp.getData())<0)
{
temp.setLeftNode(delete(temp.getLeftNode(),value));
}
else{
if(temp.getLeftNode()==null && temp.getRightNode()==null)
{
temp = null;
}
else if(temp.getLeftNode()==null && temp.getRightNode()!=null)
{
temp.setLeftNode(temp.getRightNode());
}
else if(temp.getRightNode()==null && temp.getLeftNode()!=null)
{
temp.setRightNode(temp.getLeftNode());
}
}//end else
}
return temp;
}
Explanation / Answer
Few more changes i think
private TN delete(TN temp, E value)
{
if (temp!=null)
{
if(value.compareTo(temp.getData())>0)
{
temp.setRightNode(delete(temp.getRightNode(),value));
}
else if(value.compareTo(temp.getData())<0)
{
temp.setLeftNode(delete(temp.getLeftNode(),value));
}
else{
if(temp.getLeftNode()==null && temp.getRightNode()==null)
{
temp = null;
}
else if(temp.getLeftNode()==null && temp.getRightNode()!=null)
{
temp=temp.getRightNode();
}
else if(temp.getRightNode()==null && temp.getLeftNode()!=null)
{
temp=temp.getLeftNode();
}
}//end else
}
return temp;
}
Previously, you were not removing temp but rahter resetting its right or left child if it had none.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.