当我运行将代码添加到BST的代码时,我认为只应在树的开头或JOptionPane
为空时才显示r
消息。
对于delete方法,我可以输入值,但不会删除节点数据,或者我会收到一条JOptionPane
消息,说明它不在列表中。
public boolean addToBST(int num)
{
Root = addToBST(Root, num);
return true;
}
private Node addToBST(Node r, int key)
{
if (r == null)
{
JOptionPane.showMessageDialog(null,"Empty Tree! This will be your root!");
r = new Node(key, null, null);
return r;
}
else{
if(key < r.getData())
{
r.setLeft(addToBST(r.getLeft(), key));
return r;
}
else
{
r.setRight(addToBST(r.getRight(), key));
return r;
}
}
}
public void DeleteFromBST(int key)
{
DeleteFromBST(Root, key);
}
private Node DeleteFromBST(Node r, int key)
{
if(r == null)
{
JOptionPane.showMessageDialog(
null,
" Tree Empty, can not delete "+key,
" Can NOT delete",
JOptionPane.WARNING_MESSAGE);
return null;
}
if(key < r.getData())
{
r.setLeft(DeleteFromBST(r.getLeft(),key));
}
else if (key > r.getData())
{
r.setRight(DeleteFromBST(r.getRight(),key));
}
else
{
if (r.getLeft() == null && r.getRight() == null)
{
r = null;
}
else if (r.getLeft() == null)
{
r = r.getRight();
}
else if(r.getRight() == null)
{
r = r.getLeft();
}
else
{
Node L = r.getRight();
if(L.getLeft()==null)
{
r.setData(L.getData());
r.setRight(L.getRight());
}
else
{
Node t = r;
while(L.getLeft()!=null)
{
t = L;
L = L.getLeft();
}
r.setData(L.getData());
t.setData(L.getData());
}
}
}
return r;
}