Advertisement
Five_NT

[C++]Arbori binari cu pointeri

Mar 17th, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct nod
  6. {
  7.     int cheie;
  8.     nod *st, *dr;
  9. };
  10. nod *rad, *p;
  11. int val;
  12.  
  13. void adauga(nod *&c, int val)
  14. {
  15.     if(c != 0)
  16.         if(c->cheie == val)
  17.             cout<<"Acest nod exista deja!";
  18.         else if(c->cheie < val)
  19.             adauga(c->dr, val);
  20.         else
  21.             adauga(c->st, val);
  22.     else
  23.     {
  24.         c = new nod;
  25.         c->cheie = val;
  26.         c->st = 0;
  27.         c->dr = 0;
  28.     }
  29. }
  30.  
  31. void preord (nod *p)
  32. {
  33.     cout<<p->cheie<<" ";
  34.     if(p->st != 0) preord(p->st);
  35.     if(p->dr != 0) preord(p->dr);
  36. }
  37.  
  38. void inord (nod *p)
  39. {
  40.     if(p->st != 0) inord(p->st);
  41.     cout<<p->cheie<<" ";
  42.     if(p->dr != 0) inord(p->dr);
  43. }
  44.  
  45. void postord (nod *p)
  46. {
  47.     if(p->st != 0) postord(p->st);
  48.     if(p->dr != 0) postord(p->dr);
  49.     cout<<p->cheie<<" ";
  50. }
  51.  
  52. void cauta (nod *p, int x)
  53. {
  54.     if(p==NULL)
  55.         cout<<"Nu exista informatia in arbore.\n";
  56.     else if(x < p->cheie)
  57.         cauta(p->st, x);
  58.     else if(x > p->cheie)
  59.         cauta(p->dr, x);
  60.     else
  61.         cout<<"Nodul cautata a fost gasit.\n";
  62. }
  63.  
  64. int main()
  65. {
  66.     rad=NULL;
  67.     do
  68.     {
  69.         cout<<"Dati valoarea: "; cin>>val;
  70.         if(val != 0) adauga(rad, val);
  71.     }
  72.     while(val != 0);
  73.     cout<<"\n Parcurgearea in preordine: "<<endl;
  74.     preord(rad);
  75.     cout<<"\n Parcurgerea in inordine: "<<endl;
  76.     inord(rad);
  77.     cout<<endl;
  78.     cout<<"\n Parcurgerea in postordine: "<<endl;
  79.     postord(rad);
  80.     cout<<endl;
  81.     cout<<"\n Informatia de cautat: "; cin>>val;
  82.     cauta(rad, val);
  83.     cout<<endl;
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement