I am using ref so that it changes the root of the Binary Search Tree I am trying to create, however, it's not working the way I intend for it to.
public BinaryNode<T> Root { get; set; }
public BinaryTree() : base()
{
Root = null;
public T Insert(ref BinaryNode<T> root, T val)
{
// Insert here
if (root == null)
{
BinaryNode<T> newNode = new BinaryNode<T>(val);
root = newNode;
Size++;
return val;
}
if (val.CompareTo(root.Data) < 0)
{
BinaryNode<T> left = root.LeftChild;
return Insert(ref left, val);
}
else if (val.CompareTo(root.Data) > 0)
{
BinaryNode<T> right = root.RightChild;
return Insert(ref right, val);
}
return val;
}
public override T Insert(T val)
{
BinaryNode<T> root = Root;
return Insert(ref root, val);
}
I was expecting that when I do root = newNode
that for example Root would change during the first insert. However, this is not the case. Root stays null even after. I am suspecting that this is something more related to properties and how it interacts with ref instead of ref itself?