Hi all! i write because ive a little problem with a c++ binary tree. I wrote all the cose, and the program runs, but i have a dubt: the destructor and the copy constructor. i wrote in 3 files: nodo.h, albero.h and albero.cpp (nodo means node, albero means tree)
template<class T>class Albero;
template<class T>class Nodo
{
friend class Albero<T>;
private:
T dato;
Nodo<T> *destro;
Nodo<T> *sinistro;
public:
Nodo(const T &d):destro(0), dato(d), sinistro(0){}
T getdata() const{return dato;}
};
#ifndef ALBERO_H
#define ALBERO_H
#include "nodo.h"
template<class T>class Albero
{
public:
Albero();
~Albero();
void Cancella();
void inserisciNodo(const T &);
private:
Nodo<T> *radice; ->>>>>>>>>>>>>>>>>>radice = root
void CancellaAiuto(Nodo<T> *);
void inserisciNodoAiuto(Nodo<T>**, const T &);
};
template<class T>Albero<T>::Albero()
{
radice =0;
}
template<class T>Albero<T>::~Albero()
{
Cancella();
cout<<"Distruggo l'albero\n";
}
template<class T>void Albero<T>::inserisciNodo(const T &dato)
{
inserisciNodoAiuto(&radice, dato);
}
template<class T>void Albero<T>::Cancella()
{
CancellaAiuto(radice);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T>void Albero<T>::inserisciNodoAiuto(Nodo<T> **ptr, const T &dato)
{
if(*ptr==0){
*ptr = new Nodo<T>(dato);
}
else
if(dato < (*ptr)->dato)
inserisciNodoAiuto(&((*ptr) ->sinistro), dato);
else
if(dato >(*ptr) ->dato)
inserisciNodoAiuto(&((*ptr) ->destro), dato);
else
cout<<dato<<"duplicato!"<<endl;
}
template<class T>void Albero<T>::CancellaAiuto(Nodo<T> *ptr)
{
if( ptr != NULL )
{
CancellaAiuto( ptr->sinistro );
CancellaAiuto( ptr->destro );
delete ptr;
}
}
so my question is if, in your opinion, the destructor i wrote is correct, and if i need a copy constructor in this program. I searched in web, in books but i didn't understand if i need to write it.. the program does a visit (i deleted from the code now) and performs a BST Sort.
P.S. i write from italy, so tell me if i have to transalte some words in the code :) and sorry for my english