Reputation: 41
I was wondering if someone could help me.
I want to delete a node in a C# tree and the code below does it perfectly. but what I don't fully understand is all of the nodes that are declared in the process of traversing and deleting are just copies of the actual nodes and I can't see how they can affect the actual nodes and swap them with each other. I had no problem using this kind of method in C++ because I used pointers and two pointers could simultaneously point to one chunk of memory however we don't do it in C#.
class BinarySearchTree<T>
{
class Node
{
public Node Left;
public T Info;
public Node Right;
}
public bool DeleteItem(T item)
{
Node t = Root, s = null;
while (t != null && Compare(item, t.Info) != 0)
{
s = t;
t = (Compare(item, t.Info) <= 0) ? t.Left : t.Right;
}
if (t == null)
return false;
if (t.Left != null && t.Right != null) //node has 2 children
{
Node suc = t.Right, parent_suc = null;
while (suc.Left != null)
{
parent_suc = suc;
suc = suc.Left;
}
if (parent_suc == null)
t.Right = suc.Right;
else
parent_suc.Left = suc.Right;
t.Info = suc.Info;
}
else //node has either one child or no child at all
{
Node child = t.Left;
if (t.Right != null)
child = t.Right;
if (s == null)
Root = child;
else
{
if (s.Left == t)
s.Left = child;
else
s.Right = child;
}
}
return true;
}
}
Upvotes: 0
Views: 420
Reputation: 10051
Your Node
type is a class, which is a reference type. That means that when you assign or copy it to a new variable, it will create a new reference to the original data, instead of copying the data itself (the opposite would be value type). It is indeed very similar to C++ pointers, with some differences (without pointer arithmetics, but with automatic garbage collection).
See this MSDN article about C# types, and this one about C++ pointers and C# references.
Upvotes: 3