Post

Trie (트라이)

1. 트라이 (Trie)

  • 문자열을 저장하고 빠르게 탐색하기 위한 트리 형태의 자료구조
  • 정렬된 트리구조
  • 문자열 저장을 위한 메모리가 필요하지만 탐색이 빠름
  • 길이가 N인 문자열 탐색의 시간 복잡도 : O(N)
    • 생성 복잡도 : O(MN)
    • M : 문자열 갯수

2. 트라이 형태

  • 문자열 구성
    • apple, april, ace, bear, best

    Untitled

3. 트라이 - 삽입 (1)

  • 삽입 문자열 : apple

    Untitled 1

4. 트라이 - 삽입 (2)

  • 삽입 문자열 : april

    Untitled 2

5. 트라이 - 삽입 (3)

  • 삽입 문자열 : app (플래그 표시를 한다)

    Untitled 3

6. 트라이 - 삭제 (1)

  • 삭제 문자열 : apple

    Untitled 4

7. 트라이 - 삭제 (2)

  • 삭제 문자열 : app (플래그 표시한 p를 표시 해제 한다)

    Untitled 5

8. 트라이 구현

  • Key, Value로 이루어진 노드로 구성
    • Key : 알파벳
    • Value : 자식 노드

      Untitled 6

    Untitled 7

(실습 : Trie 예제)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// 비선형 자료구조 - 트라이 (Trie)

import java.util.HashMap;

class Node {
    HashMap<Character, Node> child;
    boolean isTerminal;

    public Node() {
        this.child = new HashMap<>();
        this.isTerminal = false;
    }
}

class Trie {
    Node root;
    public Trie() {
        this.root = new Node();
    }

    public void insert (String str) {
        Node cur = this.root;

        for (int i = 0 ; i < str.length() ; i++) {
            char c = str.charAt(i);

            cur.child.putIfAbsent(c, new Node());
            cur = cur.child.get(c);

            if (i == str.length()-1) {
                cur.isTerminal = true;
                return;
            }
        }
    }

    public boolean search(String str) {
        Node cur = this.root;

        for (int i = 0 ; i < str.length() ; i++) {
            char c = str.charAt(i);

            if (cur.child.containsKey(c)) {
                cur = cur.child.get(c);
            } else {
                return false;
            }

            if (i == str.length() - 1) {
                if (!cur.isTerminal) {
                    return false;
                }
            }
        }
        return true;
    }

    public void delete(String str) {
        boolean ret = this.delete(this.root, str, 0);
        if (ret) {
            System.out.println(str + " 삭제 완료 ");
        } else {
            System.out.println(str + " 단어가 없습니다.");
        }
    }

    public boolean delete(Node node, String str, int idx) {
        char c = str.charAt(idx);

        if (!node.child.containsKey(c)) {
            return false;
        }

        Node cur = node.child.get(c);
        idx++;

        if (idx == str.length()) {
            if (!cur.isTerminal) {
                return false;
            }

            cur.isTerminal = false;

            if (cur.child.isEmpty()) {
                node.child.remove(c);
            }
        } else {
            if (!this.delete(cur, str, idx)) {
                return false;
            }

            if (!cur.isTerminal && cur.child.isEmpty()) {
                node.child.remove(c);
            }
        }
        return true;
    }
}

public class Main {
    public static void main(String[] args) {
        // Test code
        Trie trie = new Trie();
        trie.insert("apple");
        trie.insert("april");
        trie.insert("app");
        trie.insert("ace");
        trie.insert("bear");
        trie.insert("best");
        System.out.println(trie.search("apple"));   // true
        System.out.println(trie.search("april"));   // true
        System.out.println(trie.search("app"));      // true
        System.out.println(trie.search("ace"));     // true
        System.out.println(trie.search("bear"));    // true
        System.out.println(trie.search("best"));    // true
        System.out.println(trie.search("abc"));     // false

        System.out.println();
        trie.delete("apple");
        System.out.println(trie.search("apple"));   // false
        System.out.println(trie.search("april"));   // true
        System.out.println(trie.search("appl"));    // false
        trie.delete("apple");
    }
}
This post is licensed under CC BY 4.0 by the author.