Hi all,
I'm not sure how to go about asking this... I need to delete a node. What I have works on a specific data set, but not another. I read in two data sets as follows;
A 28
A 19
A 34
A 2
R 2
A 51
A 28
R 16
R 19
P
This returns:
2 this is the item being removed
28 has already been added to the list
16 this is the item being removed
19 this is the item being removed
28 34 51
** the prints are to
test, the actual output would be the last line.
The second data set is;
A 11
A 21
A 31
A 41
A 51
R 11
A 11
A 21
R 31
R 41
P
This output is;
11 this is the item being removed
Something is wrong!
11 has already been added to the list
21 has already been added to the list
31 this is the item being removed
41 this is the item being removed
11 21 31 41 51
The code I have is;
public void remove(T item)
{
BinaryNode<T> p = root, pp = null, s = null, ps = null;
//Look for item in the tree
while ( p != null && item.compareTo(p.getData()) != 0 ) {
pp = p;
if ( item.compareTo(p.getData()) > 0 )
p = p.getRightChild();
else if ( item.compareTo(p.getData()) < 0 )
p = p.getLeftChild();
}
System.out.println( item + " this is the item being removed");
// swap nodes
if ( p != null ) {
// go to the left
s = p.getLeftChild();
// then all the way to the right
if( s != null && s.getRightChild() != null ) {
ps = s;
s = ps.getRightChild();
}
if(pp != null)
pp.setLeftChild(s);
else
System.err.println("Something is wrong!");
if ( s != null ) {
ps.setRightChild(p.getLeftChild());
s.setLeftChild(p.getLeftChild());
}
}
}
I have a main class that reads in the data and iterates it in ascending order, what am I doing wrong?
Thanks in advance