I am trying to implement a simple C++ function that adds a node to a Binary Search Tree given the value of the node to be inserted, and the root of the BST.
Surprisingly, I am not able to push any element. Although I made sure that the statement where I am inserting the node is entered by the compiler, the tree did not have any of the nodes I am trying to add. I think the problem could be in how I am passing the node in the function argument. Anyone can help? Thank you. Here’s my Node type and the implementation of the function.
struct Node{
int value;
Node *left;
Node *right;
};
//this method adds a new node with value v to Binary Search Tree
// node is initially the root of the tree
void Push_To_BST(Node* node,int v)
{
// the right place to add the node
if(node==NULL)
{
node=new Node();
node->value= v;
node->left= NULL;
node->right=NULL;
}
//the value to be added is less than or equal the reached node
else if(v <= node->value)
{
//adding the value to the left subtree
Push_To_BST(node->left,v);
}
//the value to be added is greater than the reached node
else if(v > node->value)
{
//adding the value to the right subtree
Push_To_BST(node->right,v);
}
}
Careful with your referencing, there.
The
nodeyou are allocating memory to is a local variable. You would need to pass in aNode**in order to pass out a pointer to a freshly created node.Example:
and call it like