SearchDelete(ProcuraArvoreApaga) function breakpoint - c

I have a problem on the function ProcuraArvoreApaga which is a TreeSearchDelete function. I can't delete anything and when I try to delete the root it gives me a breakpoint.
When I try to delete the root I get the folowing breakpoint:
Exception thrown: read access violation.
raiz was 0xCCCCCCCC.
Here is the full code if you want to try by yourself or help me.
I use Visual Studio 2015
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
typedef struct tree *Arvore;
struct tree {
Arvore left;
Arvore right;
int *valor;
};
void DestruirNode(Arvore *raiz);
void ProcuraArvoreApaga(Arvore *raiz, int *value);
Arvore CriarArvore(int value) {
Arvore node;
if ((node = (Arvore)malloc(sizeof(struct tree))) == NULL) {
return NULL;
}
if ((node->valor = (int*)malloc(sizeof(int))) == NULL) {
return NULL;
}
*node->valor = value;
node->left = NULL;
node->right = NULL;
return node;
}
void DestruirArvore(Arvore *node) {
free((*node)->valor);
free(*node);
*node = NULL;
}
void Inserir(Arvore *raiz, int value) {
Arvore node = *raiz;
Arvore anterior = NULL;
if (*raiz == NULL) {
*raiz = CriarArvore(value);
return;
}
else {
while (node != NULL) {
anterior = node;
if (*node->valor > value) {
node = node->left;
}
else if (*node->valor < value) {
node = node->right;
}
else {
return;
}
}
if (*anterior->valor > value) {
anterior->left = CriarArvore(value);
}
else {
anterior->right = CriarArvore(value);
}
}
}
void ImprimirArvore(Arvore raiz, int nivel) {
int i;
if (raiz == NULL) {
for (i = 0; i < nivel; i++) {
printf("\t");
}
printf("*\n");
return;
}
ImprimirArvore(raiz->right, nivel + 1);
for (i = 0; i < nivel; i++) {
printf("\t");
}
printf("%d\n", *raiz->valor);
ImprimirArvore(raiz->left, nivel + 1);
}
Arvore Minimo(Arvore *raiz) {
Arvore node = *raiz;
while (node->left != NULL) {
node = node->left;
}
return node;
}
void DestruirNode(Arvore *raiz) {
Arvore node = *raiz;
if ((*raiz)->left == NULL && (*raiz)->right == NULL) {
DestruirArvore(raiz);
}
else if ((*raiz)->right == NULL) {
*raiz = (*raiz)->left;
DestruirArvore(raiz);
}
else {
*(*raiz)->valor = *Minimo((*raiz)->right)->valor;
ProcuraArvoreApaga(&(*raiz)->right, (*raiz)->valor);
}
}
void ProcuraArvoreApaga(Arvore *raiz, int *value) {
if (*raiz == NULL) {
return;
}
if (*(*raiz)->valor > *value) {
ProcuraArvoreApaga(&(*raiz)->right, value);
}
else if (*(*raiz)->valor < *value) {
ProcuraArvoreApaga(&(*raiz)->left, value);
}
else {
/*value = *(*raiz)->valor;*/
printf("%d", value);
DestruirNode(&raiz);
}
return 0;
}
int main(void) {
setlocale(LC_ALL, "Portuguese");
Arvore raiz = NULL;
int i = 0, escolha;
int value = NULL;
int var = NULL;
for (i = 1; i < 2; i++) {
printf("\t\tÁrvores binárias\n\n");
printf("Selecione a operação que deseja efetuar:\n");
printf("[1] Adicionar valor\n");
printf("[2] Vizualizar árvore\n");
printf("[3] Apagar valor/árvore\n");
printf("[4] Sair\n\n");
printf(">>");
scanf("%d", &escolha);
switch (escolha) {
case 1:
system("cls");
printf("Introduza o valor a adicionar à árvore:\n>>");
scanf("%d", &value);
Inserir(&raiz, value);// Adiciona na árvore
system("cls");
i = 0;
break;
case 2:
system("cls");
printf("\t\tVisualização da árvore\n\n");
ImprimirArvore(raiz, 10);// O 10 adiciona quantos níveis tem a árvore
i = 0;
break;
case 3:
system("cls");
printf("Introduza o valor que deseja apagar(um valor que não seja folha apagará os ramos e folhas abaixo dele):\n>>");
scanf("%d", &var);
ProcuraArvoreApaga(&raiz, &var);
system("cls");
i = 0;
break;
case 4:
break;
}
}
}

Related

how do i fix this code that _ insert zone, delete_zone, print_zone

For the creation of the map, the user is left with the possibility of requesting the following four functions via a menu with one (switch):
Insertion of a zone at the end of the insert_zone function list. It creates the new zone in dynamic memory malloc, inserts it in the list by modifying the value of the next_zone pointer of the last land in the list with the result of the malloc. The type of the zone as well as the object found within the zone are randomly generated: all zones are equiprobable, no_object has a 40% probability while the other objects in the enum Object_type_zone have equal probability. Finally, the enum field Tipo_prova prova will be inserted with a certain probability every time a player arrives in a given zone see function advance .
Delete the last zone inserted in the path cancel_zone
Print the fields of all the zones created up to that moment print_map.
i leaves the possibility to the user to use a menu to perform the following four functions:
insert_zone: delete_zone: print_map;
.
I leave a copy of the file.h (works well); "you can help to find the solution for the problem"
#ifndef H_GAMELIB
#define H_GAMELIB
extern void imposta_gioco();
extern void gioca();
extern void termina_gioco();
extern void inserisci_zona();
extern void stampa_mappa();
extern void chiudi_mappa();
extern void cancella_zona();
enum Tipo_Difficolta { dilettante, intermedio, incubo };
enum Tipo_oggetto_iniziale { EMF, spirit_box, videocamera, calmanti, sale };
enum Tipo_oggetto_zona { adrenalina, cento_dollari, coltello, calmanti1, nessun_oggetto };
enum Tipo_zona { caravan, cucina, soggiorno, camera, bagno, garage, seminterrato };
enum Tipo_prova { prova_EMF, prova_spirit_box, prova_videocamera, nessuna_prova };
struct Zona_mappa {
enum Tipo_zona zona;
enum Tipo_prova prova;
enum Tipo_oggetto_zona oggetto_zona;
struct Zona_mappa* prossima_zona;
};
struct Giocatore {
char nome_giocatore[30];
unsigned char sanita_mentale;
struct Zona_mappa* posizione;
unsigned char zaino[4];
};
#endif
main.c
#include "gamelib.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
int main (void){
unsigned short numero;
int c = 0;
printf("\033[1;35m ____ ____ ____ ____ ____ ____ ____ ____ \n");
printf(" ||P |||h |||a |||l |||s |||o |||P |||h ||\n");
printf(" ||__|||__|||__|||__|||__|||__|||__|||__||\n");
printf(" |/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|\n");
printf("\033[0m\n");
printf("||preme 'invio' per continuare||\n");
while(getchar()!= '\n');
do{
printf("\n");
printf("> \033[1;93m1\033[1m: Imposta Gioco.\n");
printf("> \033[1;96m2\033[2m: Gioca.\n");
printf("> \033[1;91m3\033[3m: Termina gioco.\n\n");
printf ("\033[92mScelta:\033[0m ");
scanf("%hu",&numero);
while ((c = getchar()) != '\n' && c != EOF); //pulizia dei buffer
switch(numero){
case 1:
printf("hai inserito il primo numero\n");
imposta_gioco();
break;
case 2:
printf("hai inserito il secondo numero\n");
gioca();break;
case 3:
printf("hai inserito il terzo numero");
termina_gioco();break;
default: printf("\033[31mAttenzione!\033[0m Opzione non valida, per favore inserisci \033[31mun numero da 1 a 3\033[0m.\n");
}
}while (numero != 3);
return 0;
}
gamelib.c
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
#include "gamelib.h"
#define ERROR_ARGS_NUM(_min, _max) printf("\033[31mAttenzione!\033[5m Opzione non valida, per favore inserisci \033[31mun numero da " #_min " a " #_max "\033[0m.\n")
#define CHECK_NUM_INPUT_RANGE(n, _min, _max)
struct Zona_mappa *pLast = NULL;
struct Zona_mappa *pFirst = NULL;
static struct Giocatore players[4];
static int nplayers = 0;
static int difficulty_level;
int ask_num(const char *prompt)
{
if (prompt)
printf("%s", prompt);
int n;
if (scanf("%d", &n) <= 0)
n = -1;
return n;
}
void mostra_zaino(struct Giocatore *giocatore)
{
const char *nome_oggetto_iniziale;
switch (giocatore->zaino[0])
{
case EMF:
nome_oggetto_iniziale = "EMF";
break;
case spirit_box:
nome_oggetto_iniziale = "Spirit Box";
break;
case videocamera:
nome_oggetto_iniziale = "Videocamera";
break;
case calmanti:
nome_oggetto_iniziale = "Calmanti";
break;
case sale:
nome_oggetto_iniziale = "Sale";
break;
default:
return;
}
printf("Contenuto zaino di %s:\nOggetto iniziale: %s\n", giocatore->nome_giocatore, nome_oggetto_iniziale);
for (int i = 1; i < 3; i++)
{
switch (giocatore->zaino[i])
{
case cento_dollari:
printf("100$\n");
break;
case nessun_oggetto:
printf("nessun_oggetto\n");
break;
case coltello:
printf("coltello\n");
break;
case calmanti1:
printf("calmanti1\n");
break;
case adrenalina:
printf("adrenalina\n");
break;
}
}
printf("\n");
}
void imposta_gioco()
{
srand(time(NULL));
memset(players, 0, sizeof(players));
nplayers = ask_num("Inserisci il numero di giocatori (da 1 a 4): ");
CHECK_NUM_INPUT_RANGE(nplayers, 1, 4);
printf("Scegli il livello di difficoltà:\n");
printf("> \033[1;93m1\033[0m: Dilettante\n");
printf("> \033[2;93m2\033[0m: Intermedio\n");
printf("> \033[3;93m3\033[0m: Incubo\n");
difficulty_level = ask_num("\033[32mInserisci il numero corrispondente: ");
CHECK_NUM_INPUT_RANGE(difficulty_level, 1, 3);
for (int i = 0; i < nplayers; i++)
{
printf("Inserisci il nome del giocatore %d: ", (i + 1));
if (scanf("%s", players[i].nome_giocatore) <= 0)
return;
players[i].sanita_mentale = 100;
players[i].zaino[0] = rand() % 5;
for (int j = 1; j < 4; j++)
players[i].zaino[j] = nessun_oggetto;
mostra_zaino(&players[i]);
}
}
struct Zona_mappa *genera_mappa()
{
// Crea la prima zona mappa
struct Zona_mappa *prima_zona = malloc(sizeof(struct Zona_mappa));
prima_zona->zona = cucina;
// Crea la seconda zona mappa
struct Zona_mappa *seconda_zona = malloc(sizeof(struct Zona_mappa));
seconda_zona->zona = soggiorno;
prima_zona->prossima_zona = seconda_zona;
// Crea la terza zona
struct Zona_mappa *terza_zona = malloc(sizeof(struct Zona_mappa));
terza_zona->zona = garage;
seconda_zona->prossima_zona = terza_zona;
struct Zona_mappa *quarta_zona = malloc(sizeof(struct Zona_mappa));
quarta_zona->zona = camera;
terza_zona->prossima_zona = quarta_zona;
// Crea la terza zona
struct Zona_mappa *quinta_zona = malloc(sizeof(struct Zona_mappa));
quinta_zona->zona = bagno;
quarta_zona->prossima_zona = quinta_zona;
struct Zona_mappa *ultima_zona = malloc(sizeof(struct Zona_mappa));
ultima_zona->zona = seminterrato;
quinta_zona->prossima_zona = ultima_zona;
ultima_zona->prossima_zona = prima_zona;
// Assegna i valori ai puntatori globali
pFirst = prima_zona;
pLast = ultima_zona;
printf("la lista è pronta\n");
return prima_zona; // Restituisce l'indirizzo della prima zona
}
void inserisci_zona()
{
struct Zona_mappa *nuova_zona = malloc(sizeof(struct Zona_mappa));
if (nuova_zona == NULL)
{
fprintf(stderr, "ERRORE di allocazione di memoria per la nuova zona\n");
return;
}
nuova_zona->zona = rand() % 4;
int r = rand() % 100;
if (r < 80)
{
nuova_zona->zona = cucina;
}
else if (r < 60)
{
nuova_zona->zona = bagno;
}
else if (r < 50)
{
nuova_zona->zona = garage;
}
else if (r < 40)
{
nuova_zona->zona = seminterrato;
}
else if (r < 30)
{
nuova_zona->zona = camera;
}
else
{
nuova_zona->zona = soggiorno;
}
r = rand() % 100;
if (r < 40)
{
nuova_zona->oggetto_zona = nessun_oggetto;
}
else if (r < 60)
{
nuova_zona->oggetto_zona = calmanti1;
}
else if (r < 70)
{
nuova_zona->oggetto_zona = coltello;
}
else if (r < 90)
{
nuova_zona->oggetto_zona = cento_dollari;
}
else
{
nuova_zona->oggetto_zona = adrenalina;
}
// Insert the new zone at the end of the list
if (pFirst == NULL)
{// If the list is empty, set First and Last as the new zone
pFirst = nuova_zona;
pLast = nuova_zona;
pLast->prossima_zona = pFirst;
}
else
{
pLast->prossima_zona = nuova_zona;
pLast = nuova_zona;
pLast->prossima_zona = pFirst;
}
}
void cancella_zona()
{
// Special case: the list is empty
if (pFirst == NULL)
{
return;
}
// Special case: the list contains a single zone
if (pFirst == pLast)
{
free(pFirst);
pFirst = NULL;
pLast = NULL;
return;
}
// Otherwise, find the last zone in the list and delete it
struct Zona_mappa *p = pFirst;
while (p->prossima_zona != pLast)
{
p = p->prossima_zona;
}
free(pLast);
pLast = p;
pLast->prossima_zona = pFirst;
}
void stampa_mappa()
{
// Caso particolare: la lista è vuota
if (pFirst == NULL)
{
printf("La mappa è vuota\n");
return;
}
printf("Stampa della mappa:\n");
struct Zona_mappa *p = pFirst;
do
{
printf(" - Zona di tipo %d, con oggetto %d\n", p->zona, p->oggetto_zona);
p = p->prossima_zona;
} while (p != pFirst);
}
void chiudi_mappa()
{
gioco_impostato = 1;
}
// Funzione che avvia il gioco
void gioca()
{
{
}
}
// Funzione che termina il gioco
void termina_gioco()
{
}
I have problems in the following 3 blocks of code
void inserisci_zona()
{
struct Zona_mappa *nuova_zona = malloc(sizeof(struct Zona_mappa));
if (nuova_zona == NULL)
{
fprintf(stderr, "ERRORE di allocazione di memoria per la nuova zona\n");
return;
}
nuova_zona->zona = rand() % 4;
int r = rand() % 100;
if (r < 80)
{
nuova_zona->zona = cucina;
}
else if (r < 60)
{
nuova_zona->zona = bagno;
}
else if (r < 50)
{
nuova_zona->zona = garage;
}
else if (r < 40)
{
nuova_zona->zona = seminterrato;
}
else if (r < 30)
{
nuova_zona->zona = camera;
}
else
{
nuova_zona->zona = soggiorno;
}
r = rand() % 100;
if (r < 40)
{
nuova_zona->oggetto_zona = nessun_oggetto;
}
else if (r < 60)
{
nuova_zona->oggetto_zona = calmanti1;
}
else if (r < 70)
{
nuova_zona->oggetto_zona = coltello;
}
else if (r < 90)
{
nuova_zona->oggetto_zona = cento_dollari;
}
else
{
nuova_zona->oggetto_zona = adrenalina;
}
// Insert the new zone at the end of the list
if (pFirst == NULL)
{// If the list is empty, set First and Last as the new zone
pFirst = nuova_zona;
pLast = nuova_zona;
pLast->prossima_zona = pFirst;
}
else
{
pLast->prossima_zona = nuova_zona;
pLast = nuova_zona;
pLast->prossima_zona = pFirst;
}
}
void cancella_zona()
{
// Special case: the list is empty
if (pFirst == NULL)
{
return;
}
// Special case: the list contains a single zone
if (pFirst == pLast)
{
free(pFirst);
pFirst = NULL;
pLast = NULL;
return;
}
// Otherwise, find the last zone in the list and delete it
struct Zona_mappa *p = pFirst;
while (p->prossima_zona != pLast)
{
p = p->prossima_zona;
}
free(pLast);
pLast = p;
pLast->prossima_zona = pFirst;
}
void stampa_mappa()
{
// Caso particolare: la lista è vuota
if (pFirst == NULL)
{
printf("La mappa è vuota\n");
return;
}
printf("Stampa della mappa:\n");
struct Zona_mappa *p = pFirst;
do
{
printf(" - Zona di tipo %d, con oggetto %d\n", p->zona, p->oggetto_zona);
p = p->prossima_zona;
} while (p != pFirst);
}
Here's the fixed code. Required modifications to fix the code are marked and explained with comments at the end of the lines starting with "// Edit:". It is a single file where I inserted the header file. At the end is a small main() to test the code.
#include <stdlib.h>
#include <stdio.h>
#ifndef H_GAMELIB
#define H_GAMELIB
void imposta_gioco (void);
void gioca (void);
void termina_gioco (void);
void inserisci_zona(void);
void stampa_mappa (void);
void chiudi_mappa (void);
void cancella_zona (void);
enum Tipo_Difficolta { dilettante, intermedio, incubo };
enum Tipo_oggetto_iniziale { EMF, spirit_box, videocamera, calmanti, sale };
enum Tipo_oggetto_zona { adrenalina, cento_dollari, coltello, calmanti1, nessun_oggetto };
enum Tipo_zona { caravan, cucina, soggiorno, camera, bagno, garage, seminterrato };
enum Tipo_prova { prova_EMF, prova_spirit_box, prova_videocamera, nessuna_prova };
struct Zona_mappa {
enum Tipo_zona zona;
enum Tipo_prova prova;
enum Tipo_oggetto_zona oggetto_zona;
struct Zona_mappa* prossima_zona;
};
struct Giocatore {
char nome_giocatore[30];
unsigned char sanita_mentale;
struct Zona_mappa* posizione;
unsigned char zaino[4];
};
#endif
static struct Zona_mappa* pFirst = NULL; // Edit: Added since pFirst was missing
static struct Zona_mappa* pLast = NULL; // Edit: Added since pLast was missing
void inserisci_zona(void) {
struct Zona_mappa* nuova_zona = malloc(sizeof(struct Zona_mappa));
if (nuova_zona == NULL)
{
fprintf(stderr, "ERROR of memory allocation for the new zone\n");
return;
}
nuova_zona->zona = rand() % 7; // Edit: enum has 7 enumerators
// Edit: Since zones are equiprobable, above line is sufficient
/*
int r = rand() % 100;
if (r < 80)
{
nuova_zona->zona = cucina;
}
else if (r < 60)
{
nuova_zona->zona = bagno;
}
else if (r < 50)
{
nuova_zona->zona = garage;
}
else if (r < 40)
{
nuova_zona->zona = seminterrato;
}
else if (r < 30)
{
nuova_zona->zona = camera;
}
else
{
nuova_zona->zona = soggiorno;
}
*/
int r = rand() % 100;
if (r < 40)
{
nuova_zona->oggetto_zona = nessun_oggetto;
}
else if (r < 55) // Edit: No object has 40% and all others 15%
{
nuova_zona->oggetto_zona = calmanti1;
}
else if (r < 70)
{
nuova_zona->oggetto_zona = coltello;
}
else if (r < 85) // Edit: No object has 40% and all others 15%
{
nuova_zona->oggetto_zona = cento_dollari;
}
else
{
nuova_zona->oggetto_zona = adrenalina;
}
// Insert the new zone at the end of the list
if (pFirst == NULL)
{
// If the list is empty, set First and Last as the new zone
pFirst = nuova_zona;
pLast = nuova_zona;
pLast->prossima_zona = NULL; // Edit: Next of last one has to be NULL
}
else
{
pLast->prossima_zona = nuova_zona;
pLast = nuova_zona;
pLast->prossima_zona = NULL; // Edit: Next of last one has to be NULL
}
}
void cancella_zona(void) {
// Special case: the list is empty
if (pFirst == NULL)
{
return;
}
// Special case: the list contains a single zone
if (pFirst == pLast)
{
free(pFirst);
pFirst = NULL;
pLast = NULL;
return;
}
// Otherwise, find the second to last zone in the list
struct Zona_mappa *p = pFirst;
while (p->prossima_zona != pLast)
{
p = p->prossima_zona;
}
free(pLast);
pLast = p;
pLast->prossima_zona = NULL; // Edit: Next of last zone has to be NULL
}
void stampa_mappa(void) {
// Special case: the list is empty
if (pFirst == NULL)
{
printf("The map is empty\n");
return;
}
printf("Map printing:\n");
struct Zona_mappa *p = pFirst;
do
{
printf(" - Zone of type %d, with object %d\n", p->zona, p->oggetto_zona);
p = p->prossima_zona;
} while (p != NULL); // Edit: Iterate until there's no next Zona_mappa which is the case if next is NULL
}
int main(void) {
stampa_mappa();
inserisci_zona();
inserisci_zona();
inserisci_zona();
stampa_mappa();
cancella_zona();
stampa_mappa();
cancella_zona();
cancella_zona();
stampa_mappa();
for (;;);
return 0;
}

reverte height of AVL tree

I'm trying to implement an AVL tree for the first time, and apparently it worked, but I need to change the way of marking the height of the tree, the root node is getting the highest height, but I want to change the root node to have height 0 and go incrementing for the child nodes.
#include <stdio.h>
#include <stdlib.h>
struct NO{
int info;
int altura;
struct NO *esq;
struct NO *dir;
};
typedef struct NO* ArvAVL;
ArvAVL* cria_ArvAVL(){
ArvAVL* raiz = (ArvAVL*) malloc(sizeof(ArvAVL));
if(raiz != NULL)
*raiz = NULL;
return raiz;
}
void libera_NO(struct NO* no){
if(no == NULL)
return;
libera_NO(no->esq);
libera_NO(no->dir);
free(no);
no = NULL;
}
void libera_ArvAVL(ArvAVL* raiz){
if(raiz == NULL)
return;
libera_NO(*raiz);//libera cada nó
free(raiz);//libera a raiz
}
int altura_NO(struct NO* no){
if(no == NULL)
return -1;
else
return no->altura;
}
int fatorBalanceamento_NO(struct NO* no){
return labs(altura_NO(no->esq) - altura_NO(no->dir));
}
int maior(int x, int y){
if(x > y)
return x;
else
return y;
}
void emOrdem_ArvAVL(ArvAVL *raiz){
if(raiz == NULL)
return;
if(*raiz != NULL){
emOrdem_ArvAVL(&((*raiz)->esq));
//printf("%d\n",(*raiz)->info);
printf("%d,%d\n",(*raiz)->info,altura_NO(*raiz));
emOrdem_ArvAVL(&((*raiz)->dir));
}
}
void RotacaoLL(ArvAVL *A){
printf("RotacaoLL\n");
struct NO *B;
B = (*A)->esq;
(*A)->esq = B->dir;
B->dir = *A;
(*A)->altura = maior(altura_NO((*A)->esq),altura_NO((*A)->dir)) + 1;
B->altura = maior(altura_NO(B->esq),(*A)->altura) + 1;
*A = B;
}
void RotacaoRR(ArvAVL *A){
printf("RotacaoRR\n");
struct NO *B;
B = (*A)->dir;
(*A)->dir = B->esq;
B->esq = (*A);
(*A)->altura = maior(altura_NO((*A)->esq),altura_NO((*A)->dir)) + 1;
B->altura = maior(altura_NO(B->dir),(*A)->altura) + 1;
(*A) = B;
}
void RotacaoLR(ArvAVL *A){
RotacaoRR(&(*A)->esq);
RotacaoLL(A);
}
void RotacaoRL(ArvAVL *A){
RotacaoLL(&(*A)->dir);
RotacaoRR(A);
}
int insere_ArvAVL(ArvAVL *raiz, int valor){
int res;
if(*raiz == NULL){
struct NO *novo;
novo = (struct NO*)malloc(sizeof(struct NO));
if(novo == NULL)
return 0;
novo->info = valor;
novo->altura = 0;
novo->esq = NULL;
novo->dir = NULL;
*raiz = novo;
return 1;
}
struct NO *atual = *raiz;
if(valor < atual->info){
if((res = insere_ArvAVL(&(atual->esq), valor)) == 1){
if(fatorBalanceamento_NO(atual) >= 2){
if(valor < (*raiz)->esq->info ){
RotacaoLL(raiz);
}else{
RotacaoLR(raiz);
}
}
}
}else{
if(valor > atual->info){
if((res = insere_ArvAVL(&(atual->dir), valor)) == 1){
if(fatorBalanceamento_NO(atual) >= 2){
if((*raiz)->dir->info < valor){
RotacaoRR(raiz);
}else{
RotacaoRL(raiz);
}
}
}
}else{
printf("Valor duplicado!!\n");
return 0;
}
}
atual->altura = maior(altura_NO(atual->esq),altura_NO(atual->dir)) + 1;
return res;
}
struct NO* procuraMenor(struct NO* atual){
struct NO *no1 = atual;
struct NO *no2 = atual->esq;
while(no2 != NULL){
no1 = no2;
no2 = no2->esq;
}
return no1;
}
int remove_ArvAVL(ArvAVL *raiz, int valor){
if(*raiz == NULL){
printf("valor não existe!!\n");
return 0;
}
int res;
if(valor < (*raiz)->info){
if((res = remove_ArvAVL(&(*raiz)->esq,valor)) == 1){
if(fatorBalanceamento_NO(*raiz) >= 2){
if(altura_NO((*raiz)->dir->esq) >= altura_NO((*raiz)->dir->dir))
RotacaoRR(raiz);
else
RotacaoRL(raiz);
}
}
}
if((*raiz)->info < valor){
if((res = remove_ArvAVL(&(*raiz)->dir, valor)) == 1){
if(fatorBalanceamento_NO(*raiz) >= 2){
if(altura_NO((*raiz)->esq->dir) >= altura_NO((*raiz)->esq->esq) )
RotacaoLL(raiz);
else
RotacaoLR(raiz);
}
}
}
if((*raiz)->info == valor){
if(((*raiz)->esq == NULL || (*raiz)->dir == NULL)){
struct NO *oldNode = (*raiz);
if((*raiz)->esq != NULL)
*raiz = (*raiz)->esq;
else
*raiz = (*raiz)->dir;
free(oldNode);
}else {
struct NO* temp = procuraMenor((*raiz)->dir);
(*raiz)->info = temp->info;
remove_ArvAVL(&(*raiz)->dir, (*raiz)->info);
if(fatorBalanceamento_NO(*raiz) <= -2){
if(altura_NO((*raiz)->esq->dir) >= altura_NO((*raiz)->esq->esq))
RotacaoLL(raiz);
else
RotacaoLR(raiz);
}
}
if (*raiz != NULL)
(*raiz)->altura = maior(altura_NO((*raiz)->esq),altura_NO((*raiz)->dir)) + 1;
return 1;
}
(*raiz)->altura = maior(altura_NO((*raiz)->esq),altura_NO((*raiz)->dir)) + 1;
return res;
}
int main()
{
ArvAVL* avl;
int res,i;
int N = 7, dados[7] = {4,5,1,2,3,7,6};
avl = cria_ArvAVL();
for(i=0;i<N;i++){
res = insere_ArvAVL(avl,dados[i]);
}
printf("\nAVL tree:\n");
emOrdem_ArvAVL(avl);
printf("\n\n");
remove_ArvAVL(avl,6);
printf("\nAVL tree:\n");
emOrdem_ArvAVL(avl);
printf("\n\n");
remove_ArvAVL(avl,7);
printf("\nAVL tree:\n");
emOrdem_ArvAVL(avl);
printf("\n\n");
remove_ArvAVL(avl,4);
printf("\nAVL tree:\n");
emOrdem_ArvAVL(avl);
printf("\n\n");
libera_ArvAVL(avl);
return 0;
}
Current output
1,0
2,1
3,0
4,2
5,0
6,1
7,0
Expected output
1,2
2,1
3,2
4,0
5,2
6,1
7,2
AVL Tree
4
/ \
2 6
/ \ / \
1 3 5 7

How to remove necessary nodes from a binary tree?

Good evening forum members.
The following is on the agenda:
Read a sequence of coordinates (x, y, z) of spatial points from the file, ordered by distance from the point of origin (develop a separate function for calculating the distance and store this value in the data structure);
To bypass use the bottom option from right to left;
Extract from the tree all nodes whose z coordinate falls within the specified range zmin ..zmax (I decided to take from 7 to 14) and indicate their number;
To completely erase the tree, use the direct (from the root) version of the bypass from left to right;
Print the entire tree using a non-recursive function.
Please help with number 3. It is not possible to implement the deletion algorithm according to a given condition. It either does not work at all, or errors arrive (
Thanks in advance to everyone who responds
CODE:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_LEN 8
#define STACK_INIT_SIZE 20
typedef struct Tree {
int z;
int viddal;
struct Tree* left, * right;
} TREE;
typedef struct Stack {
size_t size, limit;
TREE** data;
} STACK;
int Distance(FILE* ftxt, int* vid, int* z_cord);
int CreateTreeFromFile(void);
TREE* NewNode(FILE* f, int viddal, int z);
void AddNewNode(TREE* pnew);
void PrintTreeNIZ(TREE* proot);
void iterPostorder(TREE* root);
void OutputTreeStructure(const char* title);
void ShowTree(TREE* proot, int level);
void ShowLevels(void);
int TreeHeight(TREE* proot);
void EraseTree(TREE* proot);
void DeleteSomeNodes(void);
int DeleteNode(TREE* pnew_adr);
TREE* root;
int main(){
system("chcp 1251");
if (CreateTreeFromFile() == 0)
return 0;
puts("\n Created tree: ");
PrintTreeNIZ(root);
OutputTreeStructure("of created tree");
DeleteSomeNodes();
OutputTreeStructure("of the new tree");
EraseTree(root);
root = NULL;
puts("\n Tree was deleted from DM\n\n");
return 0;
}
int Distance(FILE* ftxt, int *vid, int* z_cord) {
TREE* pel = (TREE*)malloc(sizeof(TREE));
if (feof(ftxt)) {;
return NULL;
}
else {
int x, y, z;
fscanf(ftxt, "%d%d%d", &x, &y, &z);
*z_cord = z;
*vid = sqrt(x * x + y * y + z * z);
}
}
int CreateTreeFromFile()
{
const char* fname = "Cords_1.txt";
FILE* fvoc = fopen(fname, "r");
if (fvoc == NULL) {
printf("\n\t\tCan`t open file %s...\n", fname);
return 0;
}
TREE* node;
int viddal, z;
Distance(fvoc, &viddal, &z);
while ((node = NewNode(fvoc, viddal, z)) != NULL) {
AddNewNode(node);
Distance(fvoc, &viddal, &z);
}
fclose(fvoc);
return 1;
}
TREE* NewNode(FILE* f, int viddal, int z)
{
TREE* pel;
pel = (TREE*)malloc(sizeof(TREE));
if (feof(f)) {
return NULL;
}
pel->viddal = viddal;
pel->z = z;
pel->left = pel->right = NULL;
return pel;
}
void AddNewNode(TREE* pnew) {
if (root == NULL) {
root = pnew;
return;
}
TREE* prnt = root;
do {
if (pnew->viddal == prnt->viddal) {
free(pnew);
return;
}
if (pnew->viddal < prnt->viddal) {
if (prnt->left == NULL) {
prnt->left = pnew;
return;
}
else
prnt = prnt->left;
}
else {
if (prnt->right == NULL) {
prnt->right = pnew;
return;
}
else
prnt = prnt->right;
}
} while (1);
}
void PrintTreeNIZ(TREE* proot)
{
if (proot == NULL)
return;
printf("\n Right Tree");
iterPostorder(proot->right);
printf("\n\n Left Tree");
iterPostorder(proot->left);
printf("\n\n Korin - %d", proot->viddal);
}
void OutputTreeStructure(const char* title)
{
printf("\n\n\n Structur%s:\n\n", title);
ShowLevels();
ShowTree(root, 0);
puts("\n");
}
#define TAB 7
void ShowTree(TREE* proot, int level)
{
if (proot == NULL) return;
ShowTree(proot->right, level + 1);
printf("\n%*c%d", level * TAB + 10, ' ', proot->viddal);
ShowTree(proot->left, level + 1);
}
void ShowLevels(void)
{
int lev;
printf(" Level: ");
for (lev = 1; lev <= TreeHeight(root); lev++)
printf(" %-*d", 6, lev);
printf("\n\n");
}
int TreeHeight(TREE* proot)
{
int lh, rh;
if (proot == NULL) return 0;
lh = TreeHeight(proot->left);
rh = TreeHeight(proot->right);
return lh > rh ? lh + 1 : rh + 1;
}
void EraseTree(TREE* proot)
{
if (proot == NULL)
return;
EraseTree(proot->left);
EraseTree(proot->right);
free(proot);
}
STACK* createStack() {
Stack* tmp = (Stack*)malloc(sizeof(Stack));
tmp->limit = STACK_INIT_SIZE;
tmp->size = 0;
tmp->data = (TREE**)malloc(tmp->limit * sizeof(TREE*));
return tmp;
}
void freeStack(Stack** s) {
free((*s)->data);
free(*s);
*s = NULL;
}
void push(Stack* s, TREE* item) {
if (s->size >= s->limit) {
s->limit *= 2;
s->data = (TREE**)realloc(s->data, s->limit * sizeof(TREE*));
}
s->data[s->size++] = item;
}
TREE* pop(Stack* s) {
if (s->size == 0) {
exit(7);
}
s->size--;
return s->data[s->size];
}
TREE* peek(Stack* s) {
return s->data[s->size - 1];
}
void iterPostorder(TREE* root) {
Stack* ps = createStack();
TREE* lnp = NULL;
TREE* peekn = NULL;
while (!ps->size == 0 || root != NULL) {
if (root) {
push(ps, root);
root = root->left;
}
else {
peekn = peek(ps);
if (peekn->right && lnp != peekn->right) {
root = peekn->right;
}
else {
pop(ps);
printf("\n\t Visited -> %d", peekn->viddal);
lnp = peekn;
}
}
}
freeStack(&ps);
}
// HELP WITH THAT
//--------------------------------------------------------------------------------------------
void DeleteSomeNodes(void)
{
printf("\n\t Deleting needing nods:\n");
TREE* pfind = (TREE*)malloc(sizeof(TREE));
do {
if (pfind->z >= 7 && pfind->z <= 14) {
DeleteNode(root);
printf(" Number %d was deleted from tree\n", root);
}
} while (1);
puts("\n\n");
}
#define NoSubTree 0
#define LeftSubTree -1
#define RightSubTree 1
#define TwoSubTrees 2
int DeleteNode(TREE* pnew_adr)
{
TREE* proot = root;
int subtr;
if (proot == NULL) return 0;
if (pnew_adr->viddal < proot->viddal)
return DeleteNode(proot->left);
if (pnew_adr->viddal > proot->viddal)
return DeleteNode(proot->right);
if (proot->left == NULL && proot->right == NULL)
subtr = NoSubTree;
else if (proot->left == NULL)
subtr = RightSubTree;
else if (proot->right == NULL)
subtr = LeftSubTree;
else
subtr = TwoSubTrees;
switch (subtr) {
case NoSubTree:
root = NULL; break;
case LeftSubTree:
root = proot->left; break;
case RightSubTree:
root = proot->right; break;
case TwoSubTrees:
TREE* pnew_root = proot->right, * pnew_prnt = proot;
while (pnew_root->left != NULL) {
pnew_prnt = pnew_root;
pnew_root = pnew_root->left;
}
pnew_root->left = proot->left;
if (pnew_root != proot->right) {
pnew_prnt->left = pnew_root->right;
pnew_root->right = proot->right;
}
root = pnew_root;
}
free(proot);
return 1;
}
//--------------------------------------------------------------------------------------------

Trying to limit a list in C

right now i'm trying to build a simple program as my homework for college, this was supposed to be a simple code but i'm learning c just now and i'm having a really bad time trying to learn it, anyways, this code should be able to add to add, remove, show and clear some numbers on the console, a list(i dont know if it's called that way in english), but 1 thing that i can't do and i have been researching and tryed to figure out is in how to put a limit on this list, exactly 20 numbers.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *prox;
};
typedef struct node Fila;
int t;
int menu(void);
void opcao(Fila *f, int op);
void inicia(Fila *f);
int vazia(Fila *f);
Fila *aloca();
void insere(Fila *f);
Fila *retira(Fila *f);
void exibe(Fila *f);
void libera(Fila *f);
void liberar_mem(Fila *f);
int main(void)
{
Fila *f = (Fila *)malloc(sizeof(Fila));
if (!f)
{
printf("Sem memoria disponivel!\n");
exit(1);
}
else
{
inicia(f);
int opt;
do
{
opt = menu();
opcao(f, opt);
} while (opt);
free(f);
return 0;
}
}
int menu(void)
{
int opt;
printf("Escolha a opcao\n");
printf("0. Sair\n");
printf("1. Zerar solicitacoes\n");
printf("2. Exibir solicitacoes\n");
printf("3. Inserir o numero da solicitacao\n");
printf("4. Remover solicitacao\n");
printf("Opcao: ");
scanf("%d", &opt);
return opt;
}
void opcao(Fila *f, int op)
{
Fila *tmp;
switch (op)
{
case 0:
liberar_mem(f);
break;
case 1:
libera(f);
inicia(f);
break;
case 2:
exibe(f);
break;
case 3:
insere(f);
break;
case 4:
tmp = retira(f);
if (tmp != NULL)
{
printf("Solicitacao removida: %3d\n\n", tmp->num);
free(tmp);
}
break;
default:
printf("Comando invalido\n\n");
}
}
void inicia(Fila *f)
{
f->prox = NULL;
t = 0;
}
int vazia(Fila *f)
{
if (f->prox == NULL)
return 1;
else
return 0;
}
Fila *aloca()
{
Fila *novo = (Fila *)malloc(sizeof(Fila));
if (!novo)
{
printf("Sem memoria disponivel!\n");
exit(1);
}
else
{
printf("Insira o numero da solicitacao: ");
scanf("%d", &novo->num);
return novo;
}
}
void insere(Fila *f)
{
Fila *novo = aloca();
novo->prox = NULL;
if (vazia(f))
f->prox = novo;
else
{
Fila *tmp = f->prox;
while (tmp->prox != NULL)
tmp = tmp->prox;
tmp->prox = novo;
}
t++;
}
Fila *retira(Fila *f)
{
if (f->prox == NULL)
{
printf("Lista de solicitacoes ja esta vazia\n");
return NULL;
}
else
{
Fila *tmp = f->prox;
f->prox = tmp->prox;
t--;
return tmp;
}
}
void libera(Fila *f)
{
if (f->prox == NULL)
{
printf("Lista de solicitacoes ja esta vazia\n");
Fila *proxNode, *atual;
atual = f->prox;
while (atual != NULL)
{
proxNode = atual->prox;
free(atual);
atual = proxNode;
}
}
else
{
if (!vazia(f))
{
Fila *proxNode, *atual;
atual = f->prox;
while (atual != NULL)
{
proxNode = atual->prox;
free(atual);
atual = proxNode;
}
}
}
}
void exibe(Fila *f)
{
if (vazia(f))
{
printf("Nenhuma solicitacao cadastrada!\n\n");
return;
}
Fila *tmp;
tmp = f->prox;
printf("Fila :");
while (tmp != NULL)
{
printf("%5d", tmp->num);
tmp = tmp->prox;
}
printf("\n ");
int count;
for (count = 0; count < t; count++)
printf(" ^ ");
printf("\nOrdem:");
for (count = 0; count < t; count++)
printf("%5d", count + 1);
printf("\n\n");
}
void liberar_mem(Fila *FILA)
{
if (!vazia(FILA))
{
Fila *proxNode, *atual;
atual = FILA->prox;
while (atual != NULL)
{
proxNode = atual->prox;
free(atual);
atual = proxNode;
}
}
}
You could use a global variable that keeps track of the current length of the list and return an error message when someone tries to expand the list beyond the limit.
However, while global variables are fine for simple programs, it's considered good style for larger programs to rely upon them as little as possible.
Therefore, I'd recommend using a "list header" object. For example,
#define MAX_LIST_LENGTH 20
struct list_header {
Fila *start_of_list;
unsigned int current_length;
};

Deleting a Char array from a binary tree

Title explains it all, something weird is going on with my delete function that i cant seem to figure out. I think its getting stuck on the recursion part of the program based off of standard print statements. If anyone can help that would be greatly appreciated
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct btree
{
char name[10];
//int data;
struct btree *rlink;
struct btree *llink;
}node;
void insert(node**, char[]);
void inorder(node*);
void preorder(node*);
void postorder(node*);
int charToNum(node*);
node* findmin(node*);
node* findmax(node*);
node* del(node*, char[]);
int main(void)
{
node *root;
root = (node*)malloc(sizeof(node));
root = NULL;
int ch, x;
x = 0;
char num[10];
while (1)
{
printf("\n 1.insert2.inorder3.preorder4.postorder5.findmin6.findmax7.Delete");
printf("\n Enter your choice>");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\n Enter node to insert>");
scanf("%s", &num);
insert(&root, num);
break;
case 2:
printf("\n inorder display");
inorder(root);
break;
case 3:
printf("\n pre-order display");
preorder(root);
break;
case 4:
printf("\n post-order display");
postorder(root);
break;
case 5:
printf("\n Min in the tree is %s", findmin(root)->name);
break;
case 6:
printf("\n Max in the tree is %s", findmax(root)->name);
break;
case 7:
printf("\n enter the node to delete>");
scanf("%s", &num);
root = del(root, num);
break;
case 8:
exit(0);
}
}
}
void insert(node** h, char info[10])
{
if (*h == NULL)
{
node *temp;
temp = (node*)malloc(sizeof(node));
strcpy((temp->name), info);
//temp->name = info;
temp->llink = NULL;
temp->rlink = NULL;
*h = temp;
printf("successfully added %s\n", temp->name);
}
else if (info > (*h)->name) {
insert(&(*h)->rlink, info);
}
else if (info <(*h)->name)
insert(&(*h)->llink, info);
}
void inorder(node* h)
{
if (h != NULL)
{
inorder(h->llink);
printf("%s->", h->name);
inorder(h->rlink);
}
}
void preorder(node* h)
{
if (h != NULL)
{
printf("%s->", h->name);
preorder(h->llink);
preorder(h->rlink);
}
}
void postorder(node* h)
{
if (h != NULL)
{
postorder(h->llink);
postorder(h->rlink);
printf("%s->", h->name);
}
}
node* findmin(node* h)
{
if (h->llink == NULL)
return h;
else
findmin(h->llink);
}
node* findmax(node* h)
{
if (h->rlink == NULL)
return h;
else
findmax(h->rlink);
}
node* del(node *h, char info[])
{
if (h == NULL)
return h;
else if (info > h->name) {
printf("info > h->name\n");
h->rlink = del(h->rlink, info);
}
else if (info < h->name) {
h->llink = del(h->llink, info);
printf("info < h->name\n");
}
else
{
if (h->llink == NULL && h->rlink == NULL)
{
printf("first if excuting");
/*node *tmp;
tmp = (node*)malloc(sizeof(node));
tmp = h;*/
h = NULL;
return h;
}
else if (h->llink == NULL)
{
node *tmp;
tmp = (node*)malloc(sizeof(node));
tmp = h;
h = h->rlink;
free(tmp);
printf("else if finished\n");
}
else if (h->rlink == NULL)
{
printf("second else if is ecuting \n");
node *tmp;
tmp = (node*)malloc(sizeof(node));
tmp = h;
h = h->llink;
free(tmp);
printf("second else if finished\n");
}
else
{
printf("final else is excuting\n");
node *tmp;
tmp = (node*)malloc(sizeof(node));
tmp = findmin(h->rlink);
strcpy((h->name),tmp->name);
//h->name = tmp->name;
h->rlink = del(h->rlink, tmp->name);
free(tmp);
printf("final else finished\n");
}
}
return h;
}

Resources