开发者社区 问答 正文

Leetcode Trie Tree实现问题

1.这个算法是要实现一个trie tree, 但是我好像遇到了内存分配的问题,主要我是想要c语言实现. 报错信息的话,可以直接跑我那面那段代码,看看有什么问题。

include

#include
#include
#include

define MAX_SIZE 26

struct TrieNode {

   struct TrieNode *children[MAX_SIZE];
   bool isWord;

};

struct TrieNode* newTrieNode() {

   struct TrieNode *node = (struct TrieNode *)malloc(sizeof(struct TrieNode *));
   if (node == NULL)
       exit(1);
   int i;
   memset(node->children, 0x0, sizeof(struct TrieNode *)*26);
   node->isWord = false;
   return node;

}

void insert(struct TrieNode root, char word) {

   int i, length, index;
   length = strlen(word);
   if (length <= 0) return;
   struct TrieNode *current = root;
   for (i = 0; i < length; i++) {
       index = word[i] - 'a';
       if (current->children[index] == NULL) {
           current->children[index] = newTrieNode();
       }
       current = current->children[index];
   }
   current->isWord = true;

}

bool search(struct TrieNode root, char word) {

   int i, length, index;
   length = strlen(word);
   if (length <= 0) return true;
   struct TrieNode *current = root;
   for (i = 0; i < length; i++) {
       index = word[i] - 'a';
       current = current->children[index];
       if (current == NULL) return false;
   }
   return current->isWord;

}

int main() {

  struct TrieNode *root = newTrieNode();
   insert(root, "hello");
   printf("%d\n", search(root, "hello"));
   free(root);
   return 0;

}

展开
收起
杨冬芳 2016-05-30 20:12:26 2157 分享 版权
1 条回答
写回答
取消 提交回答
  • IT从业

    screenshot

    //void insert(struct TrieNode root, char word)// -- 参数都应该是指针
    void insert(struct TrieNode* root, char* word)
    {
    
        int i, length, index;
        length = strlen(word);
        if (length <= 0)
            return;
        struct TrieNode* current = root;
        for (i = 0; i < length; i++) {
            index = word[i] - 'a';
            if (current->children[index] == NULL) {
                current->children[index] = newTrieNode();
            }
            current = current->children[index];
        }
        current->isWord = true;
    }
    //bool search(struct TrieNode root, char word)// -- 参数是指针
    bool search(struct TrieNode* root, char* word)
    {
    
        int i, length, index;
        length = strlen(word);
        if (length <= 0)
            return true;
        struct TrieNode* current = root;
        for (i = 0; i < length; i++) {
            index = word[i] - 'a';
            current = current->children[index];
            if (current == NULL)
                return false;
        }
        return current->isWord;
    }

    其它没什么问题 ~

    int main()
    {
    
        struct TrieNode* root = newTrieNode();
        insert(root, "hello");
        printf("%d\n", search(root, "hello"));
        free(root);
        return 0;
    }
    2019-07-17 19:21:02
    赞同 展开评论
问答分类:
问答地址: