I made a simple program in C# to add a node in binary tree.
I have an object field ‘Root’ to hold the main parent Node. such that every time I add a node I traverse from the tree by retrieving the data in Parent Node.
Here is my code
public class BTNode
{
public int Value { get; set; }
public BTNode Left { get; set; }
public BTNode Right { get; set; }
public BTNode Root { get; set; }
}
public class BinaryTree
{
public BinaryTree()
{
size = 0;
Root = null; //To hold the main Parent Node
}
int size;
object Root;
public void AddNode(int value)
{
BTNode NewNode = new BTNode();
if (Root != null)
{
NewNode = (BTNode)Root; //If tree exists, Get the Root Node
}
while (NewNode.Root != null)
{
if (value < NewNode.Value)
{
NewNode.Root = NewNode.Left;
}
else if (value > NewNode.Value)
{
NewNode.Root = NewNode.Right;
}
}
size++;
NewNode.Value = value; //OBJECT 'ROOT' GETTING UPDATED AT THIS POINT
NewNode.Root = NewNode; //self pointer
NewNode.Left = null;
NewNode.Right = null;
if (size == 1)
{
Root = (object) NewNode; //if this is the Parent Node(First Node)
} //then update the Root to be the parent Node
}
}
I want to hold only parent node of the Binary Tree in ‘Root’.. I only want to execute the last line when size =1 i.e if its the first node of the tree but no matter what I do the Root gets updated for every node. I am struggling to know why this is happening, Please help me. am I missing any concpept, logic here.
Rootproperty could be typed toBTNode. This way you wouldn’t need to cast itNewNode = (BTNode)Root;is getting the root node reference. Any change you make toNewNodewill affect the root node. Are you aware of value types and reference types?Root) and not down (checking for the Left or Right nodes).Check this solution, please. It uses a simple recursive method to place the new node:
Hope this helps.
Regards