Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You are given a pointer to the root of a binary search tree and a value to be in

ID: 3833596 • Letter: Y

Question

You are given a pointer to the root of a binary search tree and a value to be inserted into the tree. Insert this value into its appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function.

Input Format

You are given a function,

node is defined as :

Output Format

Return the root of the binary search tree after inserting the value into the tree.

I cannot see what is wrong with my function:

node * insert(node * root, int value)
{
if (root = NULL) {
node* newNode = new node();
newNode->data = value;
newNode->left = newNode->right = NULL;
root = newNode;
}
else if(value <= root->data) {
root->left = insert(root->left, value);
}
else {
root->right = insert(root->right, value);
}
return root;
}

Please explain where my logic is wrong and any corrections.

Explanation / Answer

Please let me know in case of any issue.

this line is wrong:
   if (root = NULL)

It should be: if (root == NULL)

this line will throw compile time error: node* newNode = new node();
It should be : node* newNode = new node;

newNode should be returned from if statement


Corrected Code:

node * insert(node * root, int value)
{
if (root == NULL) {
node* newNode = new node;
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
else if(value <= root->data) {
root->left = insert(root->left, value);
}
else {
root->right = insert(root->right, value);
}
return root;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote