|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Senior Member
Iscritto dal: Mar 2004
Messaggi: 1455
|
[c] Binary tree
Qualcuno mi indicherebbe un algoritmo ricorsivo per ottenere il nodo con chiave massima da un albero binario (non di ricerca).
tnx.
__________________
Ciao ~ZeRO sTrEsS~ |
|
|
|
|
|
#2 |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
La prima cosa che mi viene in mente.
Attenzione - si incarta, (direi ovviamente) se si passa in ingresso un albero nullo. Codice:
// NOTICE - root MUST be != NULL
BinTree *getMaxNode (BinTree *root)
{
BinTree *p, *q;
// If root is leaf, then it is the maximum
if (!root->left && !root->right) return root;
p = root;
if (root->left)
{
q = getMaxNode (root->left);
p = (q->value > p->value) ? q : p;
}
if (root->right)
{
q = getMaxNode (root->right);
p = (q->value > p->value) ? q : p;
}
return p;
}
__________________
In God we trust; all others bring data |
|
|
|
|
|
#3 | |
|
Senior Member
Iscritto dal: Nov 2005
Città: Texas
Messaggi: 1722
|
Quote:
Codice:
void getTreeMax (BinTree *root)
{
if (!gPointMax) gPointMax = root;
if (root)
{
if (root->value > gPointMax->value) gPointMax = root;
getTreeMax (root->left);
getTreeMax (root->right);
}
}
La chiamata percio' sara' qualcosa del tipo: Codice:
gPointMax = NULL; getMaxTree (root);
__________________
In God we trust; all others bring data |
|
|
|
|
|
|
#4 |
|
Bannato
Iscritto dal: Feb 2005
Città: Roma
Messaggi: 7029
|
se gli alberi contengono solo valori postivi:
Codice:
int TreeMax(PTREE Tree) {
if (!Tree) {
return 0;
}
int Result = Tree->Value;
int LeftMax = TreeMax(Tree->Left);
if (LeftMax > Result) {
Result = LeftMax;
}
int RightMax = TreeMax(Tree->Right);
if (RightMax > Result) {
Result = RightMax;
}
return Result;
}
Ultima modifica di 71104 : 09-12-2006 alle 02:15. |
|
|
|
|
|
#5 |
|
Senior Member
Iscritto dal: Mar 2004
Messaggi: 1455
|
credo che la soluzione più elegante sia quella data da 71104.
__________________
Ciao ~ZeRO sTrEsS~ |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 01:34.



















