Hello folks I am studying binary search tree and recursion is very used in this kind of data.
I have a question, for example, I did the following function to search for an element in the tree:
int busca_Abb(Abb* r, int busca)
{
if(r == NULL)
return 0;
if(r->chave == busca)
return 1;
if(r->chave > busca)
busca_Abb(r->esq, busca);
busca_Abb(r->dir,busca);
}
But how is it possible if the function when called inside itself does not have any integer variable getting the value returned?
Complete code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define COUNT 15
typedef struct _abb Abb;
struct _abb{
int chave;
Abb* esq;
Abb* dir;
};
Abb* criar_Abb(void)
{
return NULL;
}
Abb* criarNo(int chave)
{
Abb* novo = (Abb* ) malloc(sizeof(Abb));
novo->chave=chave;
novo->dir=novo->esq=NULL;
return novo;
}
Abb* insere_Abb(Abb* r, int chave)
{
if(r == NULL)
return criarNo(chave);
else if(r->chave > chave)
r->esq = insere_Abb(r->esq, chave);
else if(r->chave < chave)
r->dir = insere_Abb(r->dir, chave);
return r;
}
void print2DUtil(Abb *root, int space)
{
int i;
if (root == NULL)
return;
space += COUNT;
print2DUtil(root->dir, space);
printf("\n");
for (i = COUNT; i < space; i++)
printf(" ");
printf("%d\n", root->chave);
print2DUtil(root->esq, space);
}
int busca_Abb(Abb* r, int busca)
{
if(r == NULL)
return 0;
if(r->chave == busca)
return 1;
if(r->chave > busca)
busca_Abb(r->esq, busca);
busca_Abb(r->dir,busca);
}
int main(void)
{
Abb* r;
r = criar_Abb();
int bus;
r = insere_Abb(r, 23);
r = insere_Abb(r, 12);
r = insere_Abb(r, 15);
r = insere_Abb(r, 25);
r = insere_Abb(r, 8);
printf("Arvore criada...\n");
print2DUtil(r, 0);
// procurar 25
bus = busca_Abb(r, 25);
if(bus)
printf("Achou o %d!!\n",25);
else
printf("Nao achou o %d!!\n",25);
//procurar 403
bus = busca_Abb(r, 403);
if(bus)
printf("Achou o %d!!\n", 403);
else
printf("Nao achou o %d!!\n", 403);
return 0;
}