Advertisement
darkjessy94

binary tree con classi - l'arocca

Nov 3rd, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Node{ //Node interno
  5. private:
  6.     int var;
  7.     Node *left, *right;
  8. public:
  9.     Node(int v, Node *l, Node *r){
  10.       var = v;
  11.       left = l;
  12.       right = r;
  13.     }
  14.     Node(int v){
  15.     var = v;
  16.     left = nullptr;
  17.     right = nullptr;
  18.     }
  19.     Node* leftChild(){return left;}
  20.     Node* rightChild(){return right;}
  21.     int value(){ return var; }
  22.     void setleft(Node* l){ left = l;}
  23.     void setright(Node* r){ right = r;}
  24. };
  25.  
  26. class Albero{
  27.   private:
  28.   Node *root; //aggregazione
  29.   public:
  30.   Albero(Node *r){root = r;}
  31.   Node* inserimento (Node *, int );
  32.   void creazione (Node *subroot, int n_nodi);
  33.   void visit(Node* n);
  34. };
  35.  
  36. void Albero :: visit(Node *subroot){
  37. if(subroot == nullptr) return; //vuoto
  38.   else{
  39.     cout<<subroot->value()<<endl; //radice
  40.     visit (subroot->leftChild()); //sinistra         VISITA PREORDER
  41.     visit (subroot->rightChild());//destra
  42.   }
  43. }
  44.  
  45. Node* Albero :: inserimento(Node *subroot, int val){
  46.   if (subroot == nullptr){
  47.     subroot = new Node(val);
  48.   }
  49.     else if(val > subroot -> value()){
  50.         subroot->setright(inserimento (subroot -> rightChild(), val));
  51.     }
  52.         else{
  53.         subroot->setleft(inserimento (subroot -> leftChild(), val));
  54.     }
  55.     return subroot;
  56. }
  57.  
  58.  
  59. void Albero :: creazione(Node *subroot, int n_nodi){
  60.   int elemento;
  61.   for (int i = 0; i < n_nodi; i++){
  62.     cout << "inserisci elemento: ";
  63.     cin >> elemento;
  64.     subroot = inserimento(subroot, elemento);
  65.   }
  66. }
  67.  
  68.  
  69. int main(){
  70.  Node* radice;
  71.  Node root(10);
  72.  radice = &root;
  73.  Albero tree(radice);
  74.  tree.creazione(radice,5);
  75.  tree.visit(radice);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement