Here is a c++ function to create a BST tree from an array of integers?
It’s simple.
Take first element ,make root.
Take next array element and insert it into the tree.
Why is the loop starting from i=2 and not i=1??
node* buildtree(int a[], int len)
{
node* root=new node(a[0]);
node* temp=root;
for(int i=1;i<len;i++)
{
while(!(root->left==NULL && root->right==NULL))
{
cout<<"here"<<i<<" "<<a[i]<<" " << root->val<<"\n";
if(root->val>a[i])
root=root->left;
else
root=root->right;
}
node* currnode=new node(a[i]);
if(root->val>a[i])
root->left=currnode;
else
root->right=currnode;
if(root==NULL)
cout<<"error...never.here";
root=temp;
}
return root;
}
Thanks a lot for explaining it.I tried it another way but it only finds the root.What’s the problem in it?
node* buildtree(int a[],int len)
{ node* root=new node(a[0]);
node* curr;
for(int i=1;i<len;i++)
{ curr=root;
while(curr!=NULL)
{
if(curr->val>a[i])
curr=curr->left;
else
curr=curr->right;
}
curr=new node(a[i]);
}
return root;
}
When trying to find the point of insertion,
you only stop if both children are
NULL, so at some point or other, you will setroottoNULL. Consider the array begins with[5, 3, 6, ... ]. You start withand then try to insert the 3. Since not both children are
NULL, thewhileloop runsand the controlling condition is checked anew
segfault likely here, undefined behaviour invoked.
You should do something like