Menu
Coddy logo textTech

단어 수

Coddy의 트라이 - 자료구조 시리즈 #8 코스 레슨 — 14개 중 9번째.

현재 이 트라이(trie)에 얼마나 많은 고유한 단어들이 들어 있을까요? 별도의 카운터가 없으므로, 트리를 순회하며 isEndOfWordtrue인 노드들을 세어야 합니다.

루트에서 시작하는 깊이 우선 탐색(DFS)을 통해 한 번의 순회로 이 작업을 수행할 수 있습니다. 각 노드에 대해, 해당 노드가 단어의 끝이면 1을 더하고, 모든 자식 노드로 재귀하여 그 결과들을 합산합니다. 최종 합계가 저장된 단어의 개수가 됩니다.

이 방식은 중복을 자연스럽게 처리한다는 점에 주목하세요. "cat"을 세 번 삽입하더라도 여전히 하나의 노드만 단어의 끝으로 표시되므로 카운트는 1이 됩니다. 그 자체로 삽입된 적이 없는 접두사들도 카운트되지 않습니다. 해당 노드들은 존재하지만, isEndOfWord 값이 false이기 때문입니다.

challenge icon

챌린지

쉬움

Trie 클래스에 wordCount 메서드를 추가하세요.

이 메서드는 입력을 받지 않으며 현재 트라이(trie)에 저장된 **고유한** 단어의 수를 반환합니다. 루트부터 트라이를 탐색하며 isEndOfWordtrue인 모든 노드를 셉니다.

직접 해보기

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "trie.h"

int main() {
    Trie t;
    Trie_init(&t);
    char line[1024];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "rootIsEmpty") == 0) { printf("%s\n", TrieNode_childrenCount(t.root) == 0 ? "true" : "false"); }
        if (strcmp(cmd, "hasChild") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", t.root->children[(unsigned char)arg[0]] != NULL ? "true" : "false"); }
        if (strcmp(cmd, "insert") == 0) { char* arg = strtok(NULL, " \t"); if (arg) Trie_insert(&t, arg); }
        if (strcmp(cmd, "search") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", Trie_search(&t, arg) ? "true" : "false"); }
        if (strcmp(cmd, "startsWith") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", Trie_startsWith(&t, arg) ? "true" : "false"); }
        if (strcmp(cmd, "delete") == 0) { char* arg = strtok(NULL, " \t"); if (arg) Trie_delete(&t, arg); }
        if (strcmp(cmd, "wordCount") == 0) { printf("%d\n", Trie_wordCount(&t)); }
    }
    return 0;
}

트라이 - 자료구조 시리즈 #8의 모든 레슨