【问题标题】:TRIE data structure implementation in c++C++中的TRIE数据结构实现
【发布时间】:2020-05-17 06:35:11
【问题描述】:

我已经编写了一个简单的代码来在 C++ 中实现一个 trie 数据结构。但是当我运行这个程序时,它会给出分段错误作为输出。 请大家指正,我哪里错了。

#include <bits/stdc++.h> 
using namespace std; 

struct trienode {
    struct trienode * child[26];
    bool isEnd;

    trienode()
    {
        isEnd = false;
        for(int i = 0; i < 26; i++)
        {
            child[i] = NULL;
        }
    }
};

struct trienode * root;

void insert_str(string &s, int n)
{
    trienode * curr = root;
    int i;
    for(i = 0; i < n; i++)
    {
        int index = s[i] - 'a';
        if(curr -> child[index] == NULL)
        {
            curr -> child[index] = new trienode();
        }
        else
        {
            curr = curr -> child[index];
        }
    }

    curr -> isEnd = true;
}

int main()
{
    string s1 = "yash";
    insert_str(s1, 4);
}

【问题讨论】:

  • bits/stdc++.husing namespace std; 一样是个大问题。此外,我没有看到分配给根节点的内存。

标签: c++ data-structures trie


【解决方案1】:

您尚未为根节点分配任何内存。

通常你会有一个单独的类来处理整个特里树。然后它可以分配根节点。

class trie
{
public:
    trie()
    {
        root = new trienode();
    }
    void insert_str(string &s, int n)
    {
        ...
    }
private:
    trienode* root;
};

int main()
{
    trie t;
    string s1 = "yash";
    t.insert_str(s1, 4);
}

【讨论】:

    猜你喜欢
    • 2011-04-30
    • 2020-03-09
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多