Trie的remove方法
来源:2-7 更多和Trie字典树相关的话题
爱喝水的阿水
2022-02-16 11:21:38
请问波波老师,这样写有问题嘛?
相关代码:
public void remove(String word){
root = remove(word, root, 0);
}
// 在cur节点查找word中第index个字母,如果有这个单词且cur没有其他子节点,删除cur
private Node remove(String word, Node cur, int index){
if (index == word.length()){
if (cur.isWord) {
size--;
cur.isWord = false;
// 如果当前cur节点是叶子节点,直接返回null
if (cur.next.size() == 0)
return null;
}
return cur;
}
char c = word.charAt(index);
// 如果没找到这个字符,直接return
if (cur.next.get(c) == null)
return cur;
// 当前cur节点为被删除节点的父亲节点
if (remove(word, cur.next.get(c), index + 1) == null) {
cur.next.remove(c);
// 如果当前cur节点没有其他子节点,且不代表单词,则删去
if (cur.next.size() == 0 && !cur.isWord)
return null;
}
return cur;
}1回答
liuyubobobo
2022-02-17
赞!没有问题!:)
继续加油!:)
相似问题