Consider I have object A which is holding reference to B object type, but this time initilized to null.
A->B( == null)
I want to replace the null with object of type B which hold reference to type C.
(B->C)
.
So I will get A->B->C
.
Why isn't it possible to link them by giving the reference of B object(which holds null but probably linked to specific memory address behind the scenes and assign to it the C object instead of null so afterward it will be A->B->C?
Why I must forward the A object for being able to do this manipulation?
This question is asked for trying to understand why in the following code: insertion of new node as a child of specific Node do not work. The code is :
public void InsertNodeToTreeLDR(TreeNode newNode)
{
var currRoot = Root;
InsertNodeToTreeHelper(ref currRoot, newNode);
}
private void InsertNodeToTreeHelper(ref TreeNode currTreeRoot, TreeNode newNode)
{
if (currTreeRoot == null)
{
currTreeRoot = newNode;
return;
}
else if (newNode.Data.CompareTo(currTreeRoot.Data) >= 0)
{
var currRootLeftChild = currTreeRoot.Leftchild;
InsertNodeToTreeHelper(ref currRootLeftChild, newNode);
}
else
{
var currRootRightChild = currTreeRoot.RightChild;
InsertNodeToTreeHelper(ref currRootRightChild, newNode);
}
}
Note:
I didn't want to include all code here so, this function is part of Tree Class which hold root of type TreeNode.
Think that you already have Tree with root with data == 2 (int), and want to add new left child as with data == 1.
In my implementation the linking between the Node and its child do not work.