samedi 29 juillet 2017

no Output while preorder traversing the Tree

I'm a rookie programmer.I made a program on insertion and preorder traversal in a binary search tree. But the problem is that the preorder traversal function is not printing anything. when I try to traverse the tree, nothing is printed. I tried fixing the problem but unfortunately, I was not able to fix it...please help.....

 #include<iostream>
 #include<stdio.h>
 using namespace std;
 struct node
 {
     int data;
     struct node* left;
     struct node* right;
 };

 void insert(struct node * root,int k)
{
struct node *n,*pre;
n=(struct node *)malloc(sizeof(struct node));
n->left=NULL;
n->right=NULL;
n->data=k;
if(root==NULL)
 root=n;
else
 {
 pre=root;
 while(pre!=NULL)
 {
    if(k<pre->data)
    {  
        if(pre->left==NULL)
          {
           pre->left=n;
          }
        pre=pre->left;
    }
    else if(k>pre->data)
    {
        if(pre->right==NULL)
          {
             pre->right=n;
          }
        pre=pre->right;
    }

 }

  }
 }
 void traversal(struct node * root)
 {
 if(root!=NULL)
 {
    cout<<root->data<<endl;
    traversal(root->left);
    traversal(root->right);
 }

 }

 int main()
 {
   struct node *root=NULL;
   int i,data;
   while(1)
   {
     cout<<"1.Enter into tree"<<endl;
     cout<<"2.traverse"<<endl;
     cout<<"3.exit"<<endl;
     cin>>i;
     switch(i)
     {
        case 1:cout<<"input a number:";
               cin>>data;
               insert(root,data);
               break;
        case 2:cout<<"The elements of the tree:"<<endl;
               traversal(root);
               break;
        case 3:cout<<"Exiting.... || bye!";
               exit(0);      
               break; 
    }
   }
  }

Aucun commentaire:

Enregistrer un commentaire