diff --git a/Programmation/Code/Arbre/arbre.c b/Programmation/Code/Arbre/arbre.c new file mode 100644 index 0000000000000000000000000000000000000000..160d25172f0746d1a2969d98d85b6d9f104e5fc0 --- /dev/null +++ b/Programmation/Code/Arbre/arbre.c @@ -0,0 +1,91 @@ +#include<stdio.h> +#include <stdlib.h> + +typedef struct _node { + int cle; + struct _node *left, *right; +} node; +typedef node* tree; + +void parcours_grd(tree arbre, int n){ + if(arbre!=NULL){ + parcours_grd(arbre->left, n+1); + for(int i=0; i<n; i++){ + printf(" "); + } + printf("%d\n", arbre->cle); + parcours_grd(arbre->right, n+1); + } +} + +tree recherche(tree arbre, int cle){ + while(arbre != NULL){ + if(cle > arbre->cle){ + arbre = arbre->right; + } else if(cle < arbre->cle){ + arbre = arbre->left; + } else { + return arbre; + } + } + return arbre; +} + +int taille(tree arbre){ + if(arbre == NULL){ + return 0; + } + return 1 + taille(arbre->left) + taille(arbre->right); +} + +tree creer_noeud(int cle){ + tree res = malloc(sizeof(node)); + res->left = NULL; + res->right = NULL; + res->cle = cle; + return res; +} + + +tree trouver_parent(tree arbre, int cle){ + tree courant = arbre; + tree suivant = arbre; + while(suivant != NULL && courant->cle != cle){ + courant = suivant; + if(cle < suivant->cle){ + suivant = suivant->left; + }else if(cle > suivant->cle){ + suivant = suivant->right; + } + } + return courant; + +} + +tree inserer(tree arbre, int cle){ + tree parent = trouver_parent(arbre, cle); + if(parent==NULL){ + return creer_noeud(cle); + } + if(cle < parent->cle){ + parent->left = creer_noeud(cle); + } else if(cle > parent->cle){ + parent->right = creer_noeud(cle); + } + return arbre; +} + +int main(){ + + tree arbre = NULL; + + arbre = inserer(arbre, 10); + arbre = inserer(arbre, 7); + arbre = inserer(arbre, 25); + arbre = inserer(arbre, 12); + arbre = inserer(arbre, 38); + + parcours_grd(arbre, 0); + + printf("Taille : %d\n", taille(arbre)); +} \ No newline at end of file