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;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.