Reputation: 21
My delete function doesn't work when I try to delete node with only right child. It works when node has left child only or has both left and right.
I would like to know if this is a valid approach to this problem. I know how to write this in C++ but I need it to work in C# also.
//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);
}
Upvotes: 0
Views: 10156
Reputation: 21
Actually, your code works. I have deleted else in case of no left child and I had only an if statement following if statement so it was unreachable,
//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;
}
Upvotes: 0