This question is related to a Binary Search tree. Here is the definition of a node that I am using
struct _Node
{
_Node *Parent;
int Data;
_Node *Left;
_Node *Right;
};
Now here is the definition of the function to add a node once a root is created
void AddNode(_Node *Incoming, _Node *currentNode)
{
if(!currentNode)
{
currentNode = Incoming;
}
else if(currentNode->Data >= Incoming->Data)
{
Incoming->Parent = currentNode;
AddNode(Incoming, currentNode->Left);
}
else if(currentNode->Data < Incoming->Data)
{
Incoming->Parent = currentNode;
AddNode(Incoming, currentNode->Right);
}
}
AddNode function is based on a recursive approach. Main code is
_Node *Root= new _Node;
Root->Data = 50;
Root->Parent = nullptr;
Root->Left = nullptr;
Root->Right = nullptr;
_Node *Node2 = new _Node;
Node2->Data = 25;
Node2->Parent = nullptr;
Node2->Left = nullptr;
Node2->Right = nullptr;
_Node *Node3 = new _Node;
AddNode(Node2, Root);
Problem:
Once I come out of the add node function I find that Root node doesnot have a Left or Right Child set to Node2. According to me as pointer to a node is passed each time I should have got the node added to the Root correctly. this is not happening. Can you please help me out here to understand what mistake I am making?
Try
instead of
Same for
Right.