23.3k views
2 votes
Write a BCPL program that accepts strings from the user and builds them into a binary tree. Whenever the user types * as the input string, your program should print out the entire contents of the tree in alphabetical order, then delete the entire tree, starting again with an empty one.

1 Answer

1 vote

The program is:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

typedef struct def_nodo

{char num[500];

struct def_nodo *izq, *der;

}Tiponodo;

void inserta(Tiponodo **insert, char i[]);

void borra(Tiponodo *p);

void imprime_orden(Tiponodo *p);

int main(void)

{

char nombre[500];

Tiponodo *raiz;

raiz=NULL;

do{printf("Give me the string you want: ");

__fpurge(stdin);

gets(nombre);

inserta(&raiz,nombre);

}while(strcmp(nombre,"*")!=0);

imprime_orden(raiz);

borra(raiz);

}

void inserta(Tiponodo **insert, char i[])//In this function we insert the new string in our tree

{Tiponodo *avanza, *nuevo;

avanza=*insert;

if((nuevo=(Tiponodo *)malloc(sizeof(Tiponodo)))==NULL)

{printf("no hay espacio libre");

exit(1);

}

strcpy(nuevo->num,i);

nuevo->izq=NULL;

nuevo->der=NULL;

while(avanza!=NULL)

{

if(strcmp(avanza->num,i)<0)

{if(avanza->der!=NULL)

avanza=avanza->der;

else

{avanza->der=nuevo;

return;

}

}

if(strcmp(avanza->num, i)>=0)

{if(avanza->izq!=NULL)

avanza=avanza->izq;

else

{avanza->izq=nuevo;

return;

}

}

}

avanza=nuevo;

*insert=avanza;

}

void imprime_orden(Tiponodo *p)//we use this function to print the tree

{if(p!=NULL)

{imprime_orden(p->izq);

printf("%s \\", p->num);

imprime_orden(p->der);

}

}

void borra(Tiponodo *p)//we use this function to delete the binary tree

{if(p!=NULL)

{borra(p->izq);

borra(p->der);

free(p);

}

}

User Syreeta
by
4.8k points