Creare un albero in C++

Inclusione delle librerie (linux) e del namespace

#include <iostream>
 
using namespace std;

La struttura dell’albero che stiamo per realizzare si può trovare di seguito ed è uguale a quella nelle sezioni precedenti.

Struttura dell’albero

strcut nodo{
 char info;
 nodo *left, *right;
 nodo(char a=0, nodo *b=0, nodo *c=0){info=a,left=b,right=c;}
};

La funzione che esegue la stampa del nostro albero

void STAMPA(nodo *root){
 if(root){
   cout<<root->info<<"(";
   STAMPA(root->left);
   cout<<",";
   STAMPA(root->right);
   cout<<")";
 }else
   cout<<"_";
}

La funzione C++ che realizza l’albero è la seguente:

main(){
 
 void crea_albero{
 nodo *root=new nodo('k',0,0);
 root->left=new nodo();
 root->info='f';
 root->left->left=new nodo('h',0,0);
 root->left->right=new nodo('l',0,0);
 root->left->right->left=new nodo('m',0,0);
 root->left->right->right=new nodo('o',0,0);
 root->right=new nodo();
 root->right->info='o';
 root->right->left=new nodo('g',0,0);
 root->right->right=new nodo('z',0,0);
 root->right->right->left=new nodo('f',0,0);
 
 STAMPA(root);
 cout<<endl;
 }
}
Tothebit

About Tothebit

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site