PDA

View Full Version : [C++]Albero


Luc@s
05-06-2004, 19:48
/*
### Copyright (c) 2004 Luca Francesca
### This script is provided under the terms of the GNU General Public License
### (see http://www.gnu.org/licenses/gpl.html for the full license text.)
*/
#include <iostream>
#include <ctime>
#define __DEBUG__

using namespace std;

struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int val, TreeNode *l, TreeNode *r)
{
#if defined(__DEBUG__)
cout << "Added " << val << "\n";
#endif
this->val = val;
left = l;
right = r;
};
};

class Tree
{
private:
TreeNode *root;
void AddElem(TreeNode *aux, int val)
{
if(aux == NULL)
{
aux = new TreeNode(val, NULL, NULL);
}
else if(val <= aux->val)
AddElem(aux->left, val);
else if(val > aux->val)
AddElem(aux->right, val);
};
void InternalShowInOrder(TreeNode *P)
{
if (P->left) InternalShowInOrder(P->left);
cout << P->val << "\n";
if (P->right) InternalShowInOrder(P->right);
;}
public:
Tree(int elem)
{
root = new TreeNode(elem, NULL, NULL);
};
void Add(int val)
{
AddElem(root, val);
};
void Print()
{
InternalShowInOrder(root);
}
~Tree(){ delete root; root = NULL; };
};

int main(int argc, char *argv[])
{
Tree tr(1);
srand(time(NULL));

for(int i = 0; i < (rand()%10);i++)
{
tr.Add( i + (rand()%25) );

}
tr.Print();
char exit;
std::cin.get(exit);
return 0;
}




Perche visualizzo sempre e solo 1???

Tnk

/\/\@®¢Ø
05-06-2004, 20:21
Il problema principale e' che AddElem modifica solo la copia locale del puntatore, e non quella che e' presente nella struttura del padre.
Ti conviene cambiare il metodo facendo si' che la nuova foglia venga ritornata come valore da modificare nel padre.
Questo fra l'altro rende possibile creare l'albero vuoto con estrema semplicita':


TreeNode* AddElem(TreeNode *aux, int val)
{
if(aux == NULL)
{
return new TreeNode(val, NULL, NULL);
}
else if(val <= aux->val)
aux->left =AddElem(aux->left, val);
else if(val > aux->val)
aux->right=AddElem(aux->right, val);
return aux
};

Tree()
{
root = NULL;
};
void Add(int val)
{
root = AddElem(root, val);
};