I'm trying to create a binary search tree from a given array. The following code shows segmentation fault. I tried debugging it and found problem on the *newnode function.
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
struct node *parent;
};
struct node *newnode(int data)
{
struct node *temp;
temp->data = data;
temp->right =NULL;
temp->left = NULL;
temp->parent =NULL;
return(temp);
}
The above function seems to return the correct pointer but the in the following function T doesn't seem to accept it.
void Insert(struct node *T,int data)
{
if(T==NULL)
{
T = newnode(data); //The program shows segfault here.
return;
}
if(data>T->data) { Insert(T->right,data); T->right->parent = T; }
else { Insert(T->left,data); T->left->parent = T; }
return;
}
void Inorder(struct node *T)
{
if(T==NULL) return;
else{
Inorder(T->left);
cout<<T->data<<" ";
Inorder(T->right);
}
}
int main() {
int n; cin>>n;
struct node *tree=NULL;
for(int i=0;i<n;i++)
{
int x; cin>>x;
Insert(tree,x);
}
Inorder(tree);
return 0;
}
You have not allocated memory to temp pointer.
struct node *newnode(int data)
{
struct node *temp = new node;
temp->data = data;
temp->right = NULL;
temp->left = NULL;
temp->parent = NULL;
return temp;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.