当我尝试删除只有正确孩子的节点时,我的删除功能不起作用。它在节点仅离开子节点或左右都有效时起作用。 我想知道这是否是解决此问题的有效方法。我知道如何用C ++编写它,但我需要它在C#中工作。
//Private method, with args: root node, node to be deleted
private Node DeleteN(Node root, Node deleteNode)
{
if (root == null)
{
return root;
}
if (deleteNode.data < root.data)
{
root.left = DeleteN(root.left, deleteNode);
}
if (deleteNode.data > root.data)
{
root.right = DeleteN(root.right, deleteNode);
}
if (deleteNode.data == root.data)
{
//No child nodes
if (root.left == null && root.right == null)
{
root = null;
return root;
}
//No left child - DONT WORK
else if (root.left == null)
{
Node temp = root;
root = root.right;
temp = null;
}
//No right child
else if (root.right == null)
{
Node temp = root;
root = root.left;
temp = null;
}
//Has both child nodes
else
{
Node min = FindMin2(root.right);
root.data = min.data;
root.right = DeleteN(root.right, min);
}
}
return root;
}
//Public method with arg: int value of node to be deleted
public void DeleteNode(int x)
{
Node deleteNode = new Node(x);
DeleteN(root, deleteNode);
}
答案 0 :(得分:0)
实际上,您的代码有效。我已经删除其他,如果没有留下的孩子,我只有 if语句跟在if语句,所以它无法访问,
//No child nodes
if (root.left == null && root.right == null)
{
root = null;
return root;
}
//No left child - DONT WORK
else if (root.left == null) //WORKS NOW-missed else, it has been only if
{
Node temp = root;
root = root.right;
temp = null;
}
//No right child
else if (root.right == null)
{
Node temp = root;
root = root.left;
temp = null;
}