30.05.2013 Views

Appunti per il modulo di algoritmi e strutture dati - Sezione di ...

Appunti per il modulo di algoritmi e strutture dati - Sezione di ...

Appunti per il modulo di algoritmi e strutture dati - Sezione di ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

}<br />

}<br />

< esamina tree -> label ><br />

preOrder (tree -> left );<br />

preOrder (tree -> right );<br />

void postOrder ( Node * tree ) {<br />

if ( tree ) {<br />

postOrder (tree -> left );<br />

postOrder (tree -> right );<br />

< esamina tree -> label >;<br />

}<br />

}<br />

void inOrder ( Node * tree ) {<br />

if ( tree ) {<br />

inOrder (tree -> left );<br />

< esamina tree -> label >;<br />

inOrder (tree -> right );<br />

}<br />

}<br />

Per quanto riguarda <strong>il</strong> tempo <strong>di</strong> esecuzione, in genere la sua complessità è valutata in funzione del<br />

numero n <strong>di</strong> no<strong>di</strong> dell’albero. Supponiamo <strong>per</strong> semplicità che <strong>il</strong> tempo <strong>per</strong> l’esame del nodo sia costante.<br />

La relazione <strong>di</strong> ricorrenza <strong>per</strong> le tre visite è la seguente, dove con ns e nd in<strong>di</strong>chiamo rispettivamente <strong>il</strong><br />

numero <strong>di</strong> no<strong>di</strong> del sottoalbero sinistro e destro della ra<strong>di</strong>ce:<br />

T (0) = a<br />

T (n) = b + T (ns) + T (nd) con ns + nd = n − 1 n > 0<br />

Si noti che con a abbiamo in<strong>di</strong>cato <strong>il</strong> tempo <strong>per</strong> <strong>il</strong> test (tree) e con b <strong>il</strong> tempo <strong>per</strong> l’esame del nodo.<br />

Dimostriamo con l’induzione strutturale the T (n) = bn + a(n + 1).<br />

Base. Se l’abero è vuoto, T (0) = a e la formula è verificata.<br />

Induzione. Ipotesi: T (ns) = bns + a(ns + 1) e T (nd) = bnd + a(nd + 1)<br />

Tesi: T (n) = bn + a(n + 1).<br />

Dim.<br />

T (n) = b + T (ns) + T (nd) <strong>per</strong> la relazione <strong>di</strong> ricorrenza<br />

= b + bns + a(ns + 1) + bnd + a(nd + 1) <strong>per</strong> ipotesi induttiva<br />

= b(1 + ns + nd) + a(ns + nd + 2)<br />

= bn + a(n + 1) <strong>per</strong>chè ns + nd + 1 = n<br />

Abbiamo quin<strong>di</strong> che T (n) è lineare nel numero dei no<strong>di</strong>. Diamo ora alcune definizioni che ci saranno<br />

ut<strong>il</strong>i nel seguito.<br />

Definizione 6.2 (albero binario b<strong>il</strong>anciato)<br />

• Un albero binario b<strong>il</strong>anciato è un albero binario tale che i no<strong>di</strong> <strong>di</strong> tutti i livelli tranne quelli<br />

dell’ultimo hanno due figli.<br />

30

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!