소프트웨어 개발/Algorithm

트라이 (Trie)

Leo's notes 2019. 2. 26. 23:07

Example

#include <stdio.h>
#include <stdlib.h>

typedef struct _node {
struct _node *child[26];
int end;
} Node;

Node *createNewNode() {
Node *newNode = (Node *) malloc(sizeof(Node));
for(int i=0;i<26;i++) {
newNode->child[i] = NULL;
}
newNode->end = 0;
return newNode;
}

void push(Node *node, char *s, int depth) {
if(s[depth] == '\0') {
node->end = 1;
return;
}
int index = s[depth] - 'a';
if(node->child[index] == NULL) {
Node *newNode = createNewNode();
node->child[index] = newNode;
push(newNode, s, depth+1);
}
else push(node->child[index], s, depth+1);
}

int search(Node *node, char *s, int depth) {

if (s[depth] == '\0' && node->end) return 1;

int index = s[depth] - 'a';
if (node->child[index] == NULL) return 0;
return search(node->child[index], s, depth+1);
}

int main() {
Node *root = createNewNode();
push(root, "abc", 0);
push(root, "asdf", 0);
printf("%d\n", search(root, "abc", 0));
printf("%d\n", search(root, "abd", 0));
printf("%d\n", search(root, "ab", 0));
printf("%d\n", search(root, "sdf", 0));
printf("%d\n", search(root, "asdf", 0));
return 0;
}