首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言入門

C語言實現二叉樹詞頻統計:結構體定義、插入、中序遍歷與字符串複製陷阱

     編輯:C 語言入門

節點結構

int cmp(const char *a, const char *b) {
    for (int i = 0; a[i] == b[i]; i++)
        if (a[i] == '\0') return 0;  // 相等
    return a[i] < b[i] ? -1 : 1;     // 字典序
}

插入邏輯(遞歸)

void inorder(Node *root) {
    if (!root) return;
    inorder(root->left);
    printf("[%-20s] count: %d\n", root->word, root->count);
    inorder(root->right);
}

銷毀樹

int main(void) {
    Node *root = NULL;
    insert(&root, "hello");
    insert(&root, "hey");
    insert(&root, "hello");
    insert(&root, "ok");
    insert(&root, "hey");
    insert(&root, "hey");
    insert(&root, "hey");
    inorder(root);
    destroy(root);
    return 0;
}

輸出

[hello             ] count: 2
[hey               ] count: 4
[ok                ] count: 1

總結

二叉樹詞頻統計展示了自參考結構體、遞歸插入、字符串深拷貝、中序遍歷有序輸出四大核心技能。工程上大數據量建議用紅黑樹、Trie 樹或哈希表,但理解 BST 基礎是前提。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved