Basic Trie Tree


#include <iostream>
#include <cstdlib>
using namespace std;
#define MAX_SIZE 26


struct TrieNode {
    int char_count;
    char ch;
    TrieNode* son_char[MAX_SIZE];
};


void clear_node( TrieNode* node ) {
    node->char_count = 0;
    for ( int i = 0; i < MAX_SIZE; ++i ) {
        node->son_char[i] = NULL;
    }
}


void insert_string( TrieNode* root, string str ) {

    const int str_len  = str.length();
    TrieNode* now_node = root;

    for ( int i = 0; i < str_len; ++i ) {
        const char ch = str[i] - 'a';
        if ( now_node->son_char[ch] == NULL ) {
            TrieNode* temp = ( TrieNode* )malloc( sizeof( TrieNode ) );
            clear_node( temp );
            temp->ch = ch;
            now_node->son_char[ch] = temp;
        }
        now_node = now_node->son_char[ch];
        now_node->char_count += 1;
    }

}


int search_string( TrieNode* root, string str ) {

    TrieNode* now_node = root;
    const int str_len = str.length();

    for ( int i = 0; i < str_len; ++i ) {
        const char ch = str[i] - 'a';
        now_node = now_node->son_char[ch];
        if ( now_node == NULL )
            return 0;
    }

    return now_node->char_count;

}


void delete_node( TrieNode* node ) {
    for ( int i = 0; i < MAX_SIZE; ++i ) {
        if ( node->son_char[i] != NULL )
            delete_node( node->son_char[i] );
    }
    free( node );
}


int main() {

    TrieNode* root = ( TrieNode* )malloc( sizeof( TrieNode ) );
    clear_node( root );
    int insert_test_num;
    int search_test_num;

    cout << "Enter insert_test_num: ";
    cin >> insert_test_num;

    for ( int i = 0; i < insert_test_num; ++i ) {
        string str;
        cout << "Enter str: ";
        cin >> str;
        insert_string( root, str );
    }

    cout << "Enter search_test_num: ";
    cin >> search_test_num;

    for ( int i = 0; i < search_test_num; ++i ) {

        string str;
        cout << "Enter str: ";
        cin >> str;

        int res = search_string( root, str );
        if ( res )
            cout << "String Is In Trie Tree: " << res << " Times." << endl;
        else
            cout << "String Is Not in Trie Tree." << endl;

    }

    delete_node( root );

    return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值