Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Node{ //Node interno
- private:
- int var;
- Node *left, *right;
- public:
- Node(int v, Node *l, Node *r){
- var = v;
- left = l;
- right = r;
- }
- Node(int v){
- var = v;
- left = nullptr;
- right = nullptr;
- }
- Node* leftChild(){return left;}
- Node* rightChild(){return right;}
- int value(){ return var; }
- void setleft(Node* l){ left = l;}
- void setright(Node* r){ right = r;}
- };
- class Albero{
- private:
- Node *root; //aggregazione
- public:
- Albero(Node *r){root = r;}
- Node* inserimento (Node *, int );
- void creazione (Node *subroot, int n_nodi);
- void visit(Node* n);
- };
- void Albero :: visit(Node *subroot){
- if(subroot == nullptr) return; //vuoto
- else{
- cout<<subroot->value()<<endl; //radice
- visit (subroot->leftChild()); //sinistra VISITA PREORDER
- visit (subroot->rightChild());//destra
- }
- }
- Node* Albero :: inserimento(Node *subroot, int val){
- if (subroot == nullptr){
- subroot = new Node(val);
- }
- else if(val > subroot -> value()){
- subroot->setright(inserimento (subroot -> rightChild(), val));
- }
- else{
- subroot->setleft(inserimento (subroot -> leftChild(), val));
- }
- return subroot;
- }
- void Albero :: creazione(Node *subroot, int n_nodi){
- int elemento;
- for (int i = 0; i < n_nodi; i++){
- cout << "inserisci elemento: ";
- cin >> elemento;
- subroot = inserimento(subroot, elemento);
- }
- }
- int main(){
- Node* radice;
- Node root(10);
- radice = &root;
- Albero tree(radice);
- tree.creazione(radice,5);
- tree.visit(radice);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement