Write a function to build a binary search tree from an array. The function will
ID: 3830859 • Letter: W
Question
Write a function to build a binary search tree from an array. The function will take in the array and the array size as arguments, and return a pointer to the root of the tree.
Use the following function header:
Node *build(int a[], int size);(plz just using this function)Don't need other help function
Use the following struct:
struct Node{
int key;
Node *parent;
Node *left;
Node *right;
Node(Node *p, Node *l, Node *r){
parent = p;
left = l;
right = r;
}
};
Use the following print statements as nodes are added to the tree:
If the node is placed as the parent node:
cout<<"root: "<<root->key<<" parent: "<<parent<<endl;
If the node is placed as the left child:
cout<<"node: "<<node->key<<" left child of: "<<parent->key<<endl;
If the node is placed as the right child:
cout<<"node: "<<node->key<<" right child of: "<<parent->key<<endl;
And my code is like this:
Node *build(int a[], int size){
Node *parent = NULL;
Node *node = new Node(NULL, NULL, NULL);
if(size == 0)
{
return NULL;
}
else
{
for(int i = 0; i < size; i++)
{
if(!root)
{
root = new Node(NULL,NULL,NULL);
root->key = a[i];
cout<<"root: "<<root->key<<" parent: "<<parent<<endl;
}
else
{
parent = root;
Node *temp= parent;
while(temp!= NULL)
{
parent = temp;
if(node->key <temp->key)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
if(parent == NULL)
{
root = node;
}
else if(node->key < parent->key)
{
parent->left = node;
node->key = a[i];
node->parent = parent;
cout<<"node: "<<node->key<<" left child of: "<<parent->key<<endl;
}
else
{
parent->right = node;
node->key = a[i];
node->parent = parent;
cout<<"node: "<<node->key<<" right child of: "<<parent->key<<endl;
}
}
}
return root;
}
}
what's wrong with code? any help
Expected Got root: 45 parent 0 root 45 parent. 0 node 32 left child of 45 node 32 left child of 45 node 56 right child of 45 node 56 right child of 56 node 12 left child of 32 node 12 right child of 45 node 90 right child of 56 node: 23 right child of 12 *Time limit exceeded*** node 54 left child of 56 node: 20 left child of 23 node: 1 left child of 12 node: 234 right child of 90Explanation / Answer
consider this part of code :
while(temp!= NULL)
{
parent = temp;
if(node->key <temp->key)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
you are comparing node->key with parent->key but by this time you haven't assigned value to node -> key.
So first before comparing while creating node it self assign the value and set the reference while comparing.
This should slove your problem
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.