3
I’m making a program that allocates a dictionary in memory to check for misspelled words in text files. The function below converts dictionary words into integers and stores them in tree structures.
- My question is how to write correctly and iteratively part of code that stores the numbers in the tree(from line 24).
I saw many examples, but all recursive and did not understand very well, feel free to give any kind of example to other users who may have the same doubt.
typedef struct arvore
{
unsigned int n;
struct arvore *esq, *dir;
}arvore;
arvore *raiz;
unsigned int
BPHash(const char* str, unsigned int len)
{
unsigned int hash;
for (unsigned int i = 0; i < len; str++, i++)
hash = hash << 7 ^ (*str);
return hash;
}
bool
load(const char *dict)
{
FILE *fp = fopen(dict, "r"); // dict = arquivo que serve como dicionário
if (fp == NULL)
return false;
char str[LENGTH+1]; // LENGTH = tamanho máximo da string (45)
unsigned int strtam, hash; // Tamanho da string e string convertida em inteiro com função hash
struct arvore dicio = {0, NULL, NULL};
raiz = &dicio; // Ponteiro global
while (fgets(str, LENGTH, fp) != NULL)
{
strtam = strlen(str);
hash = BPHash(str, strtam); // BPHash = função hash
if (raiz->n == 0) // Minha dúvida se refere as linhas abaixo
raiz->n = hash;
else if (raiz->n < hash)
{
raiz->esq = (arvore*)malloc(sizeof(arvore));
raiz->dir = NULL;
raiz->n = hash;
}
else
{
raiz->dir = (arvore*)malloc(sizeof(arvore));
raiz->esq = NULL;
raiz->n = hash;
}
}
return true;
}
You could put your job
BPHash
also?– Victor Stafusa