前缀树的定义
- 前缀树是N叉树的特殊形式,用于存储字符串。
- 前缀树的每个节点代表一个字符串/前缀。
- 每个节点拥有几个子节点,子节点的值由该结点的值和通往该节点路径上所有的字符组成。
特性: 节点的后代都与该节点相关的字符串具有相同的前缀。
前缀树的表示
- 底层使用数组存储子节点
当需要存储的字符串中只有a-z的字符时可以使用数组存储子节点,通过 c - ‘a’ 来访问子节点。
class TrieNode {
// 改变这个值来适应不同的情况
public static final int N = 26;
public TrieNode[] children = new TrieNode[N];
// 更具不同的情况可能会需要额外的成员变量..
}
- 底层使用哈希表,键是字符、值是子节点
class TrieNode {
public Map<Character, TrieNode> children = new HashMap<>();
}
除了子节点的表示之外,可能还会用到其他的值,比如如果要在前缀树中存储单词,则需要一个布尔值来标注该节点所表示的字符串是否为字符串。
前缀树的基本操作
- 插入
伪代码:
1.Initialize: cur = root
2. for each char c in target string S:
3. if cur does not have a child c:
4. cur.children[c] = new Trie node
5. cur = cur.children[c]
6. cur is the node which represents the string S
- 搜索
伪代码:
1. Initialize: cur = root
2. for each char c in target string S:
3. if cur does not have a child c:
4. search fails
5. cur = cur.children[c]
6. search successes