我实现了递归算法来删除BST中的节点,但是如果要删除的节点有两个子节点,它似乎无法正常工作。以下是用于删除节点的方法的代码:
public boolean delete(int val)
{
Node nodeToBeDeleted = find(val);
if(nodeToBeDeleted != null)
{
//case 1: node has no children
if(nodeToBeDeleted.leftChild == null && nodeToBeDeleted.rightChild == null)
deleteCase1(nodeToBeDeleted);
//case 3: node has two children
else if(nodeToBeDeleted.leftChild != null && nodeToBeDeleted.rightChild != null)
{
deleteCase3(nodeToBeDeleted);
}
//case 2: node has one child
else if(nodeToBeDeleted.leftChild != null)
{
//case 2 where left child should be deleted
deleteCase2(nodeToBeDeleted);
}
else if(nodeToBeDeleted.rightChild != null)
{
//case 2 where right child should be deleted
deleteCase2(nodeToBeDeleted);
}
return true;
}
else
return false;
}
这里有deleteCase1,deleteCase2和deleteCase3方法:
private void deleteCase1(Node nodeToBeDeleted)
{
//check if node to be deleted is a left or a right child of the parent of the node to be deleted
if(nodeToBeDeleted.parent.leftChild == nodeToBeDeleted)
{
nodeToBeDeleted.parent.leftChild = null;
}
else if(nodeToBeDeleted.parent.rightChild == nodeToBeDeleted)
{
nodeToBeDeleted.parent.rightChild = null;
}
}
这里找到方法:
public Node find(int val)
{
if(root != null)
{
return findNode(root, new Node(val));
}
return null;
}
private Node findNode(Node search, Node node)
{
if(search == null)
return null;
if(search.data == node.data)
{
return search;
}
else
{
Node returnNode = findNode(search.leftChild, node);
if(returnNode == null)
{
returnNode = findNode(search.rightChild, node);
}
return returnNode;
}
}
minLeftTreversal方法:
private Node minLeftTreversal(Node node)
{
if(node.leftChild == null)
return node;
return minLeftTreversal(node.leftChild);
}
树的结构如下所示: enter image description here
算法可以正常工作,如果我删除75,但如果我尝试删除25,它就会混乱。
提前谢谢!
答案 0 :(得分:0)
public boolean delete(int val)
中的第一个if语句缺少{
和}
//case 1: node has no children
if(nodeToBeDeleted.leftChild == null && nodeToBeDeleted.rightChild == null)
{ // <---- ADD THIS
deleteCase1(nodeToBeDeleted);
} // <---- AND ADD THIS
//case 3: node has two children
else if(nodeToBeDeleted.leftChild != null && nodeToBeDeleted.rightChild != null)
{
deleteCase3(nodeToBeDeleted);
}