简体   繁体   中英

Height trie tree in C

I need to calculate the height of a trie tree in C

the node struct is as follows:

struct trie_cel {
char type; // 'I': internal / 'P': letter
struct trie_cel *child [HEIGHT_ALPHABET]; // use the function CHAR_TO_INDEX to get child node of each letter
};
typedef struct trie_cel no;

i'm trying to use recursion

if(r == NULL) return -1;
if(!r) return 0;
int alt = 0;
int heightM = 0;
no** i = r->child;
no** fim = i + (sizeof(r->child) / sizeof(no *));
while(i != end){
    alt = height(r->child[i])+1;
    if(alt > heightM){
        heightM = alt;
    }
}
return heightM;

However, my code is presented with the following problem, could anyone help me?

    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 = height(r->child[i])+1;
                                ^
chmod: cannot access 'vpl_execution': No such file or directory

I was able to calculate using "int" but i'd like to learn how to calculate using pointers

Maybe use the pointer directly 'height(*i)'. Or use pointer arithmetics to convert to integer type: 'i - r->child'

I believe this is how you should approach:

int trie_height(no *root) {
  if (root == NULL) return -1;
  int i, h = 0;
  for (i = 0; i < HEIGHT_ALPHABET; i++) {
    int res = 1 + trie_height(root->child[i]);
    if (res > h)
        h = res;
  }
  return h;
}

Since child is an array, you can't adress it's elements anything other than an integer. i isn't an integer in your code, so it wouldn't work. Also, you're doing nothing with fim after assigning it, so it's useless there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM