Advertisement
monyca98

arbori binari de cautare

May 30th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include<iostream>
  2.  using namespace std;
  3.  struct nod
  4. {   int info;
  5.     nod *s,*d;
  6. };
  7. nod *r;
  8. void creeare(nod *&r,int n)
  9. {   if(r!=NULL)
  10.         if(n<r->info)
  11.         creeare(r->s,n);
  12.         else
  13.             if(n>r->info)
  14.                 creeare(r->d,n);
  15.             else
  16.                 cout<<"valoarea citita exista in arbore"<<endl;
  17.     else
  18.     {   r=new nod;
  19.         r->info=n;
  20.         r->s=NULL;
  21.         r->d=NULL;
  22.     }
  23. }
  24. void rsd(nod *r)
  25. {   if(r!=NULL)
  26.     {   cout<<r->info<<" ";
  27.         rsd(r->s);
  28.         rsd(r->d);
  29.     }
  30. }
  31. int max(nod *r)
  32. {   if(r==NULL)
  33.         return 0;
  34.     if(r->d!=NULL)
  35.         return max(r->d);
  36.     else
  37.         return r->info;
  38. }
  39. int min(nod *r)
  40. {   if(r==NULL)
  41.         return 0;
  42.     if(r->s!=NULL)
  43.         return min(r->s);
  44.     else
  45.         return r->info;}
  46. int cautare(nod *r,int x)
  47. {   if(r==NULL)
  48.         return 0;
  49.     else
  50.         if(r->info==x)
  51.             return 1;
  52.         else
  53.             if(x<r->info)
  54.                 return cautare(r->s,x);
  55.             else
  56.                 return cautare(r->d,x);
  57. }
  58. void inserare(nod *&r,int x)
  59. {   if(r!=NULL)
  60.         if(r->info==x)
  61.             cout<<"eticheta exista"<<endl;
  62.         else
  63.             if(r->info>x)
  64.                 inserare(r->s,x);
  65.             else
  66.                 inserare(r->d,x);
  67.     else
  68.     {   r=new nod;
  69.         r->info=x;
  70.         r->s=NULL;
  71.         r->d=NULL;
  72.     }
  73. }
  74. int main ()
  75. {   int n,x;
  76.     r=NULL;
  77.     cin>>n;
  78.     while(n!=0)
  79.     {   creeare(r,n);
  80.         cin>>n;}
  81.     cin>>x;
  82.     rsd(r);
  83.     cout<<endl;
  84.     cout<<"nodul maxim este "<<max(r)<<endl;
  85.     cout<<"nodul minim este "<<min(r)<<endl;
  86.     if(cautare(r,x))
  87.         cout<<"valoarea exista"<<endl;
  88.     else
  89.         cout<<"valoarea nu exista"<<endl;
  90.     inserare(r,x);
  91.  
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement