Program got crashed on compiling

Hi! all

I'm working for implementing the binary search tree .Everything looks fine but on compiling the code , the program got crashed .

code :


#include<iostream>
#include<stdio.h>
using namespace std;

struct node{ //defining the structure for tree
int data;
node* right;
node* left;
};

typedef node* nodeptr; // providing the simple name for node pointer

nodeptr root=NULL; //setting the node pointer to null

void insert(int info,nodeptr q) //defining the insert function
{
if(root==NULL) //if root has nothing then create a node and assign it as root
{
nodeptr p=new node;

p->right=NULL;
p->left=NULL;
p->data=info;
root=p;
}
else if(info < root->data && root->left!=NULL) //otherwise compare with left
{
insert(info,root->left); //calling function using recursion
}
else if(info > root->data && root->right!=NULL)
{
insert(info,root->right);
}
else if(info < root->data && root->left==NULL) //if no left node exist then create a node and assign it as right node with two child
{
nodeptr p=new node;
p->data=info;
p->left=NULL;
p->right=NULL;

root->left=p;
return;

}
else if(info > root->data && root->right==NULL) //if no right node exist then create a node and assign it as right node with two child
{
nodeptr p=new node;
p->data=info;
p->left=NULL;
p->right=NULL;
root->right=p;
return;
}


}

//simple implementation of general tree traversing technique

void preorder(nodeptr &root)
{
if(root!=NULL)
{
cout<<root->data<<" -> ";
preorder(root->left);
preorder(root->right);
}
}

void inorder(nodeptr &root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data<<" -> ";
inorder(root->right);
}
}


int main()
{
insert(2,root); //calling defined functions here
insert(6,root);
insert(3,root);
insert(8,root);


preorder(root);

cout<<endl;

inorder(root);
cout<<endl;
return 0;
}
Your insert function does not use parameter q, trying to insert into root repeatedly, Also you should pass q by reference
Last edited on
Topic archived. No new replies allowed.