Trie is an ordered tree data structure which stores words in it so that users can search a word or a prefix quickly. Time complexity for adding a word to a Trie is $O(l)$, and for searching a word or a prefix is $O(l)$ too ($l$ is the length of the word or the prefix being added or searched). So it’s why we prefer Trie rather than Set and Hash Table in some situations, such as Dynamic Set, Associative Array and a predictive text or autocomplete Dictionary.

## Definition

• The Trie is a tree where each node represents a single word or a prefix.
• The root represents an empty string (“”), the nodes that are direct children of the root represent prefixes of length $1$, the nodes that are $2$ edges of distance from the root represent prefixes of length $2$, the nodes that are $3$ edges of distance from the root represent prefixes of length $3$ and so on. In other words, a node that is $k$ edges of distance of the root has an associated prefix of length $k$.
• Let $v$ and $w$ be two nodes of the Trie, and assume that $v$ is the parent of $w$, then $v$ must have an associated prefix of $w$.

The figure below shows a Trie with the words “TREE”, “TRIE”, “ALGO”, “ASSOC”, “ALL”, and “ALSO.”

Trie

## LeetCode Problem

### 211. Add and Search Word - Data structure design

Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters “a-z” or “.”. A “.” means it can represent any one letter.

#### For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

#### Note:

You may assume that all words are consist of lowercase letters a-z.

## Solution

Since this problem need us to find whether that word actually exists or not, so we shouldn’t treat that word as a prefix of another word. Implementing a variant Trie with a flag representing it’s an end of a word can resolve that problem discussed before.
This is the data structure called TrieNode:

So to solve this LeetCode problem, all we need now is to implement methods addWord(String word) and search(String word):