Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct tree {
- char letra;
- struct tree *izq;
- struct tree *der;
- };
- struct tree *inicio;
- void preorden(struct tree *z){
- /* raiz izquierda derecha*/
- printf("%c",z->letra);
- if (z->izq != NULL) preorden(z->izq);
- if (z->der != NULL) preorden(z->der);
- }
- void inorden(struct tree *z){
- /*izquierda raiz derecha*/
- if (z->izq != NULL) inorden(z->izq);
- printf("%c",z->letra);
- if (z->der != NULL) inorden(z->der);
- }
- void postorden(struct tree *z){
- /*izquierda derecha raiz*/
- if (z->izq != NULL) postorden(z->izq);
- if (z->der != NULL) postorden(z->der);
- printf("%c",z->letra);
- }
- void insertar (struct tree *z,char l){
- struct tree *aux = inicio;
- struct tree *ant;
- /*para empezar llenamo nuestra estructura con la letra entregada l*/
- z->letra = l;
- /*si el inicio esta en null significa que nuetro arbol esta vacio se coloca el puntero inicio en nuetra estructura*/
- if (inicio == NULL){
- inicio = z;
- z->izq=NULL;
- z->der=NULL;
- }else{
- /*si esta lleno buscamo la hoja de la cual colgara nuetra nueva estructura*/
- do{
- ant = aux;
- /*el aux empieza en inicio, si nuestra letra es mayor se va este a la izquierda si no a la derecha */
- if (l > aux->letra) aux = aux->izq;else aux = aux->der;
- }while(aux!=NULL);
- /*hasta que aux sea nulo entonces la hoja de la cual enlazaremos nuestra estructura sera ant*/
- if (l > ant->letra)ant->izq = z;else ant->der=z;
- /*si l es mayor se enlaza por la izq si es menor por la derecha*/
- z->izq = NULL;
- z->der = NULL;
- /*de nuestra hoja sus nodos a null*/
- }
- }
- void main(){
- int i = 0;
- char pal[20];
- struct tree *p;
- inicio = NULL;
- printf("\n\n\tingrese palabra > ");
- scanf("%s",&pal);
- /*en este do while se llena nuestro arbol se crea una estructura y se le pasa a insertar hunto con una letra de nuestra plabra esto se repeite hasta que se encuentra el caracter nulo*/
- do{
- p=(struct tree *) malloc (sizeof(struct tree));
- insertar(p,pal[i]);
- i++;
- }while( pal[i]!= '\0' );
- printf("\n\t\tpreorden > ");preorden(inicio);
- printf("\n\t\tinorden > ");inorden(inicio);
- printf("\n\t\tpostorden > ");postorden(inicio);
- getchar();
- printf("\n\n");
- }
Add Comment
Please, Sign In to add comment