1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct maillon *arbre; //Déclaration de pointeur sur maillon
struct maillon //Déclaration de maillon
{
int val;
arbre g;
arbre d;
};
arbre ajout_feuille(arbre A,int e) //Déclaration de fonction qui ajoute une feuille
{
arbre p;
if(A == NULL)
{
A = (arbre)malloc(sizeof(struct maillon));//allouer de la mémoire
if(A == NULL)
{
printf("impossible d'allouer");
}
else
{
A->val=e;
A->g=NULL;
A->d=NULL;
}
}
else
{
if(e <= (A->val))
{
A->g = ajout_feuille(A->g ,e);
}
else
{
A->d = ajout_feuille(A->d ,e);
}
}
return A;
}
void affichpe_arbre(arbre A)//Déclaration de fonction qui affiche un arbre
{
if(A != NULL)
{
printf("\t[%p]\n",A);
printf("[%p][%d][%p] \n\n",A->g,A->val,A->d);
affichpe_arbre(A->g);
affichpe_arbre(A->d);
}
}
arbre convert(int tab[],arbre A,int debut,int fin)
{
if(debut != (fin/2)+(debut/2) && fin != (fin/2)+(debut/2) && debut != fin)
{
A = ajout_feuille(A,tab[(fin+debut)/2]);
printf("\t[%d]\n",tab[(fin/2)+(debut/2)-1]);
printf("\t%d\t%d\t%d\t%d\n",debut,(fin/2)+(debut/2)-1,(fin/2)+(debut/2)+1,fin);
//system("pause");
convert(tab,A,debut,((fin+debut)/2)-1);
convert(tab,A,((fin+debut)/2)+1,fin);
}
return A;
}
int main (void)
{
arbre A = NULL; //Déclaration d'un arbre et initialisation a Nil
int tab[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27};
A = convert(tab,A,0,26);
// printf("arbre par infixe:\n\n");
// affichin_arbre(A);
printf("arbre par preordre:\n\n");
affichpe_arbre(A);
system("pause");
return 0;
} |
Partager