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 基礎是前提。