在BST中添加和删除节点

时间:2014-05-04 02:28:44

标签: java binary-search-tree

当我运行将代码添加到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;
} 

0 个答案:

没有答案