wood burning stoves*
The moose likes Beginning Java and the fly likes Deleting node from binary search tree Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Deleting node from binary search tree" Watch "Deleting node from binary search tree" New topic
Author

Deleting node from binary search tree

Kewl Daemon
Greenhorn

Joined: Mar 24, 2005
Posts: 3
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
bart zagers
Ranch Hand

Joined: Feb 05, 2003
Posts: 234
It would be a good idea to put code tags around your code to make it more readable.

You are not giving all the relevant code, but.
- You can get the error message only when pp is null
- it is only set in the while loop (in the visible code)
- therefore you don't get into the while loop
- check what happens when you remove the root element (is 11 the root element in the second case?).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Deleting node from binary search tree