Correction TD 11 : Structure de donn´ees arbre
Licence 2 MASS semestre 2, 2007/2008
Exercice 1
Algorithme somme(a: arbre) : entier d´ebut
siarbreEstVide?(a)alors retourner0
sinon
retourner (racine(a))2+ somme(arbreGauche(a)) + somme(arbreDroit(a)) fin si
fin
Exercice 2 : Evaluation d’expression
74 /
45 7
1.2 3.6
*
+ −
+
/
12 0
9.4
• Algorithme Eval(A: arbre d’expression) : r´eel variable v : r´eel
d´ebut
siarbreEstVide?(A)alors retourner0
sinon
siracine(A) est un nombrealors retournerracine(A)
fin si
siracine(A) est ”+”alors
retournerEval(arbreGauche(A)) + Eval(arbreDroit(A)) fin si
siracine(A) est ”-”alors
1
retournerEval(arbreGauche(A)) - Eval(arbreDroit(A)) fin si
siracine(A) est ”*”alors
retournerEval(arbreGauche(A)) * Eval(arbreDroit(A)) fin si
siracine(A) est ”/”alors v ←Eval(arbreDroit(A)) siv6= 0 alors
retournerEval(arbreGauche(A)) /v sinon
´ecrire(”Erreur : division par z´ero !!!”) retournermaxInt
fin si fin si fin si fin
• Algorithme EvalX(A : arbre d’expression;x: r´eel) : r´eel variable v : r´eel
d´ebut
siarbreEstVide?(A)alors retourner0
sinon
siracine(A) est un nombrealors retournerracine(A)
fin si
siracine(A) est ”x”alors retournerx
fin si
siracine(A) est ”+”alors
retournerEval(arbreGauche(A),x) + Eval(arbreDroit(A),x) fin si
siracine(A) est ”-”alors
retournerEval(arbreGauche(A),x) - Eval(arbreDroit(A),x) fin si
siracine(A) est ”*”alors
retournerEval(arbreGauche(A),x) * Eval(arbreDroit(A),x) fin si
siracine(A) est ”/”alors v ←Eval(arbreDroit(A),x) siv6= 0 alors
retournerEval(arbreGauche(A),x) /v sinon
´ecrire(”Erreur : division par z´ero !!!”) retournermaxInt
fin si
2
fin si fin si fin
• Algorithme Points(f: arbre d’expression;n: entier) : variable i: entier;x: r´eel
d´ebut x←a
pouride 1 `a nfaire point(x,EvalX(f,x)) x←x+b−an
fin pour fin
3