|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Senior Member
Iscritto dal: Apr 2002
Città: Vigevano(PV)
Messaggi: 2123
|
[C++]Albero
Codice:
/* ### 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; } Tnk
__________________
Gnu/Linux User ![]() |
![]() |
![]() |
![]() |
#2 |
Bannato
Iscritto dal: Jul 2000
Città: Malo (VI)
Messaggi: 1000
|
Re: [C++]Albero
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': Codice:
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); }; |
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 08:27.