May 18, 2012 at 3:03am UTC
Hi,
I was writing simple tree program and getting core dump during the traversal of tree.Could anyone provide me some insight.
#include<iostream>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
node *root =NULL;
void create_tree(int data)
{
node *temp = new node;
temp->data = data;
temp->left =NULL;
temp->right =NULL;
if(root ==NULL)
root =temp;
else
{
node *p =root;
node *trail =NULL;
while(p!=NULL)
{
trail=p;
if(p->data > data)
{
p =p->left;
}
else
{
p=p->right;
}
}
if(trail==NULL)
{
root=temp;
return;
}
if(trail->data > data)
{
trail->left =temp;
}
else
{
trail->right = temp;
}
}
}
void preorder_traverse(node *s)
{
cout<<"traversing data"<<" " ;
if(root)
{
cout<<s->data<<" ";
preorder_traverse(s->left);
preorder_traverse(s->right);
}
}
int main()
{
int data;
for(int i=0;i<3;i++)
{
cout<<"Enter data";
cin>>data;
create_tree(data);
}
cout<<"traverse :"<<endl;
preorder_traverse(root);
return 0;
}
May 18, 2012 at 4:46am UTC
Thanks a lot for your reply. Could you Pleas give some insight to fix this issue. I had impression that root is
global pointer and adding the the element into create_tree function will impact root pointer which can be use
for printing the element
May 18, 2012 at 9:03am UTC
I don't see a problem in create_tree() , but you should check for NULL of the node in the traverse