Skip to content
Snippets Groups Projects
Commit de4da5a2 authored by Pierre Kunzli's avatar Pierre Kunzli
Browse files

ajout demo arbre

parent 3a126a03
Branches
No related tags found
No related merge requests found
#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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment