Leetcode

Implement Trie (Prefix Tree)

  • Time:Time:
  • Space:Space:

C++

struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  bool isWord = false;
  TrieNode() : children(26) {}
};

class Trie {
 public:
  void insert(const string& word) {
    auto node = root;
    for (const char c : word) {
      const int i = c - 'a';
      if (!node->children[i])
        node->children[i] = make_shared<TrieNode>();
      node = node->children[i];
    }
    node->isWord = true;
  }

  bool search(const string& word) {
    auto node = find(word);
    return node && node->isWord;
  }

  bool startsWith(const string& prefix) {
    return find(prefix) != nullptr;
  }

 private:
  shared_ptr<TrieNode> root = make_shared<TrieNode>();

  shared_ptr<TrieNode> find(const string& prefix) {
    auto node = root;
    for (const char c : prefix) {
      const int i = c - 'a';
      if (!node->children[i])
        return nullptr;
      node = node->children[i];
    }
    return node;
  }
};

JAVA

class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public boolean isWord = false;
}

class Trie {
  public void insert(String word) {
    TrieNode node = root;
    for (final char c : word.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        node.children[i] = new TrieNode();
      node = node.children[i];
    }
    node.isWord = true;
  }

  public boolean search(String word) {
    TrieNode node = find(word);
    return node != null && node.isWord;
  }

  public boolean startsWith(String prefix) {
    return find(prefix) != null;
  }

  private TrieNode root = new TrieNode();

  private TrieNode find(String prefix) {
    TrieNode node = root;
    for (final char c : prefix.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        return null;
      node = node.children[i];
    }
    return node;
  }
}

Python

class Trie:
  def __init__(self):
    self.root = {}

  def insert(self, word: str) -> None:
    node = self.root
    for c in word:
      if c not in node:
        node[c] = {}
      node = node[c]
    node['isWord'] = True

  def search(self, word: str) -> bool:
    node = self.find(word)
    return node is not None and 'isWord' in node

  def startsWith(self, prefix: str) -> bool:
    return self.find(prefix) is not None

  def find(self, prefix: str) -> dict:
    node = self.root
    for c in prefix:
      if c not in node:
        return None
      node = node[c]
    return node