[leetcode]208. Implement Trie (Prefix Tree)

자몽·2025년 7월 31일

자료구조-알고리즘

목록 보기
21/22
post-thumbnail

https://leetcode.com/problems/implement-trie-prefix-tree/submissions/1717889324/
트라이 클래스를 구현해보는 문제이다.
트라이에 대한 설명은 알고달레에서 참고했다.
https://www.algodale.com/data-structures/trie/

Trie() Initializes the trie object.

void insert(String word) Inserts the string word into the trie.

boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.

boolean startsWith(String prefix) Returns true if there is a previously
inserted string word that has the prefix prefix, and false otherwise.


  1. class 기반 Trie
class TrieNode {
    constructor() {
        this.children = {};
        this.isEnd = false;
    }
}

class Trie {
    constructor() {
        this.root = new TrieNode();
    }

    insert(word) {
        let node = this.root;
        for (let char of word) {
            if (!node.children[char]) {
                node.children[char] = new TrieNode();
            }
            node = node.children[char];
        }
        node.isEnd = true;
    }

    search(word) {
        const node = this._traverse(word);
        return node !== null && node.isEnd;
    }

    startsWith(prefix) {
        return this._traverse(prefix) !== null;
    }

    _traverse(str) {
        let node = this.root;
        for (let char of str) {
            if (!node.children[char]) return null;
            node = node.children[char];
        }
        return node;
    }
}

  1. function + prototype 기반 Trie
function TrieNode() {
    this.children = {};
    this.isEnd = false;
}

function Trie() {
    this.root = new TrieNode();
}

Trie.prototype.insert = function(word) {
    let node = this.root;
    for (let char of word) {
        if (!node.children[char]) {
            node.children[char] = new TrieNode();
        }
        node = node.children[char];
    }
    node.isEnd = true;
};

Trie.prototype.search = function(word) {
    const node = this._traverse(word);
    return node !== null && node.isEnd;
};

Trie.prototype.startsWith = function(prefix) {
    return this._traverse(prefix) !== null;
};

Trie.prototype._traverse = function(str) {
    let node = this.root;
    for (let char of str) {
        if (!node.children[char]) return null;
        node = node.children[char];
    }
    return node;
};

시간 복잡도

메서드시간 복잡도설명
insertO(L)L = 단어 길이
searchO(L)L = 단어 길이
startsWithO(L)L = 접두사 길이

공간 복잡도

  • 최악의 경우: O(N × L)

    • N: 삽입된 단어 개수
    • L: 평균 단어 길이
  • 중복된 접두사가 많으면 훨씬 줄어듦 (공유 구조 덕분)


class vs prototype 방식 차이 정리

항목class 방식function + prototype 방식
문법 도입ES6 (2015년)ES5 이하
가독성높음낮음
new 없이 호출❌ 오류 발생✅ 가능
strict mode기본 적용됨수동 적용 필요
상속extends, super로 간단복잡한 수작업 필요
호이스팅❌ 안 됨✅ 가능
실질 동작둘 다 prototype 기반동일

profile
자몽의 벨로그에 오신것을 환영합니다. 티스토리 블로그(https://jamongjjang.tistory.com/)

0개의 댓글