【 數據結構 】字典樹的構建及搜索代碼實現

#include <stdio.h>
#include <stdlib.h>
#define Alphabet_SIZE 26

// 數據結構
typedef struct tnode
{
    int flag;   // 是否爲 word 節點 / word 的數量
    struct tnode *next[Alphabet_SIZE];  // 子節點
}tnode;

tnode createDictTree(char* strs[], int len);    // 爲字符串數組建立字典樹
void addNodeInTree(tnode *root, char *str);     // 爲字典樹添加 word
int searchInTree(tnode *root, char *str);       // 在字典樹中查找 word

int main(){
    char *str[] = {"hello", "hell", "world", "hbchen", "hbchen"};
    tnode root = createDictTree(str, 5);    // 建立字典樹
    int i;
    for(i = 0; i < 5; i++){
        int cnt = searchInTree(&root, str[i]);  // 查找驗證
        printf("%s:%d\n", str[i], cnt);
    }
    return 0;
}

tnode createDictTree(char* strs[], int len){
    tnode root = {0};
    int i;
    for(i = 0; i < len; i++){
        addNodeInTree(&root, strs[i]);
    }
    return root;
}

void addNodeInTree(tnode *root, char *str){
    tnode *pt = root, *next;
    char *ps = str;
    while((*ps) != '\0'){
        int idx = *ps - 'a';
        next = pt->next[idx];
        if(next == NULL){
            // 子節點不存在,創建子節點並初始化
            pt->next[idx] = (tnode*)malloc(sizeof(tnode));
            next = pt->next[idx];
            pt->flag = 0;
            int i;
            for(i = 0; i < Alphabet_SIZE; i++){
                next->next[i] = NULL;
            }
        }
        pt = next;        
        ps++;
    }
    pt->flag++; // str遍歷完成,當前節點次數+1
}

int searchInTree(tnode *root, char *str){
    // 返回詞的頻數 或 是否存在
    tnode *pt = root, *next;
    char *ps = str;
    while((*ps) != '\0'){
        // 按照 word 順序依次從 root 遍歷字典樹
        int idx = *ps - 'a';
        if(pt->next[idx] == NULL){
            return -1;
        }
        pt = pt->next[idx];
        ps++;
    }
    return pt->flag;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章