Error when calculating tree height Trie in C

Asked

Viewed 97 times

0

I need to implement a code that calculates the height of a tree Trie in the C language.

To struct of knot is the following:

struct trie_cel {
    char tipo; // 'I': interno / 'P': palavra
    struct trie_cel *filho[TAMANHO_ALFABETO]; // Utilizar a funcao CHAR_TO_INDEX para obter o no filho de cada letra.
};
typedef struct trie_cel no;

I’m trying to calculate the height of a tree Trie with recursion, this is my function:

int altura(no* r) {
    if(r == NULL) return -1;
    if(!r) return 0;
    int alt = 0;
    int alturaM = 0;
    no** i = r->filho;
    no** fim = i + (sizeof(r->filho) / sizeof(no *));
    while(i != fim){
        alt = altura(r->filho[i])+1;
        if(alt > alturaM){
            alturaM = alt;
        }
    }
    return alturaM;
}

However the following error is being presented and I am not being able to locate it.

trie.cpp: In function ‘int altura(no*)’:
trie.cpp:146:32: error: invalid types ‘trie_cel* [27][no** {aka trie_cel**}]’ for array subscript
         alt = altura(r->filho[i])+1;
                                ^

1 answer

1


The problem is you’re trying to use the type no** as an index of array, what is not possible.

You have to change these lines

no** i = r->filho;
no** fim = i + (sizeof(r->filho) / sizeof(no *));

To

int i = 0;
int fim = TAMANHO_ALFABETO;

And add 1 to the variable i every time the loop at the end of while

Or you can turn it into a for loop

int altura(no *r) {
    if(r == NULL) return -1;
    if(!r) return 0;
    int alt = 0;
    int alturaM = 0;
    for (int i = 0; i < TAMANHO_ALFABETO; i++) {
        alt = altura(r->filho[i])+1;
        if(alt > alturaM){
            alturaM = alt;
        }
    }
    return alturaM;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.