Tries
A trie (pronounced as “try”) or prefix tree is a tree data structure used for storing and searching a specific key from a set, usually a string set.
Using Trie, search complexities can be brought to O(n)(n = key length).
208. Implement Trie (Prefix Tree)
Properties
Below are some important properties of the Trie data structure1:
- There is one root node in each Trie.
- Each node of a Trie represents a string and each edge represents a character.
- Every node consists of hashmaps or an array of pointers, with each index representing a character and a flag to indicate if any string ends at the current node.
- Trie data structure can contain any number of characters including alphabets, numbers, and special characters. But for this article, we will discuss strings with characters a-z. Therefore, only 26 pointers need for every node, where the 0th index represents ‘a’ and the 25th index represents ‘z’ characters. 我们仅讨论key为
[a-z]的Trie. - Each path from the root to any node represents a word or string.
Data Structure
Every node of Trie consists of multiple branches. Each branch represents a possible character of keys:
Mark the last node of every key as the end of the word node. A Trie node field isEndOfWord is used to distinguish the node as the end of the word node.
public static class TrieNode{ |
Operations
Trie trie = new Trie(); |
public class Trie { |
Insert
每一个输入的word都对应一条path.
使用递归的思路进行插入:
// If not present, inserts key into trie. |
Search
使用递归的思路进行查找. 如果当前字符匹配且该word只剩下这1个字符(currentRoot.children[idx] != null && word.length() == 1), 那么如果当前node的isEndOfWord==false, 则返回false; 如果isEndOfWord==true, 则返回true.
public boolean search(String word) { |
StartsWith
和查找差不多, 但只要输入和某个路径的前面一部分匹配即可:
Trie trie = new Trie(); |
public boolean startsWith(String prefix) { |
https://www.geeksforgeeks.org/introduction-to-trie-data-structure-and-algorithm-tutorials/↩︎