PDA

View Full Version : Problemi BST C++


aldo90
16-07-2013, 17:15
Salve a tutti ho un problema con questo programma in C++.Mi da in output un errore di stack overflow sulla funzione visita.Penso che il problema sia di put_o che non riesce a collegare i vari nodi.
Riporto il codice:
#ifndef TREE_H
#define TREE_H
struct nodo{
int val;
int h;
nodo *sx,*dx;
};

class bst{
protected:
nodo *head;
nodo* put_o(nodo *p,int info);
void distruggi(nodo* p);
void calc_h(nodo* p,int a);
void visita(nodo* p);
nodo* copia(nodo* p);
public:
bst();
~bst();
bst(const bst &a1);
void insert(int info);
void stampa();
void altezza();
};


#endif


#ifndef TREE_CPP
#define TREE_CPP

#include "tree.h"
#include <iostream>
#include <stdlib.h>


using namespace std;

bst::bst(){
head=NULL;
}
void bst::distruggi(nodo* p){
if(p!=NULL){
distruggi(p->dx);
distruggi(p->sx);
delete p;
}
}

bst::~bst(){
distruggi(head);
}
bst::bst(const bst &a1){
head=copia(a1.head);
}
nodo* bst::copia(nodo* p){
if(p==NULL)
return NULL;
else
{
nodo *app = new nodo;
app->val = p->val;
app->sx = copia(p->sx);
app->dx = copia(p->dx);

return app;
}
}

void bst::insert(int info){
head=put_o(head,info);
}
nodo* bst::put_o(nodo *p,int info){
p=head;
if(p==NULL){
nodo *aux=new nodo;
aux->val=info;
aux->h=0;
aux->dx=NULL;
aux->sx=NULL;
p=aux;}

else{
if(p->val<info){
p->dx=put_o(p->dx,info);}
else{
p->sx=put_o(p->sx,info);}

}
return p;
}

void bst::visita(nodo *p){
visita(p->sx);
cout<<p->val;
cout<<p->h;
visita(p->dx);

}
void bst::stampa(){
visita(head);
}



#endif