I have written working code for this problem however it is not producing an output and it states is a wrong answer.
Please just fix my code below and make it work for the sample test cases and all test cases.
You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their 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 * insert (Node * root ,int data) { }
Constraints
Output Format
Return the root of the binary search tree after inserting the value into the tree.
Sample Input
4 / \ 2 7 / \ 1 3
The value to be inserted is 6.
Sample Output
4 / \ 2 7 / \ / 1 3 6
This is the code. The code that is bolded can not be changed and is part of it.
But the insert function is where we have to implement it.
Please fix my code. Thank you
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class Solution {
public:
void preOrder(Node *root) {
if( root == NULL )
return;
std::cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
Node * insert (Node * root, int value){
if (root == NULL) {
Node* newNode;
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;
}
};
int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
std::cin >> t;
while(t-- > 0) {
std::cin >> data;
root = myTree.insert(root, data);
}
myTree.preOrder(root);
return 0;
}
Node * insert (Node * root, int value){
if (root == NULL) {
Node* newNode = new Node(value);
return newNode;
}
if(value <= root->data) {
root->left = insert(root->left, value);
}
else {
root->right = insert(root->right, value);
}
return root;
}
The bold code is the code that has been changed. What you did is
correct if the Node was a struct type. but it is a class and we
have to create a object to create a node. and thats the thing i did
here.
Please make sure to like the answer. Thanks so much in
advance.
Get Answers For Free
Most questions answered within 1 hours.