본문 바로가기
Computer Science/Data Structure

[자료구조] 트라이(Trie) 구현 - 파이썬

by ggyongi 2021. 9. 7.

트라이(Trie): 검색트리의 일종으로 일반적으로 키가 문자열인, 동적 배열 또는 연관 배열을 저장하는 데 사용되는 정렬된 트리 자료구조다.

 

<트라이 구현>

class Node:
    def __init__(self):
        self.word = False
        self.children = {}

class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = Node()
            node = node.children[char]
        node.word = True

    def search(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                return False
            node = node.children[char]
        return node.word

    def startswith(self, prefix):
        node = self.root
        for char in prefix:
            if char not in node.children:
                return False
            node = node.children[char]
        return True


trie = Trie()
trie.insert('apple')
print(trie.search('apple'))    # True
print(trie.search('app'))      # False
print(trie.startswith('app'))  # True

 

📘 비전공자 개발자 취업 성공기 시리즈

개발자가 되고 싶었던 한 비전공자의 1년 4개월 이야기
막막했던 시작부터 좌절, 그리고 합격까지의 여정을 기록했습니다

 

비전공자 네카라 신입 취업 노하우

시행착오 끝에 얻어낸 취업 노하우가 모두 담긴 전자책!

kmong.com

댓글