Trie add和contain 递归写法
public void addR(String word) {
addR(root, 0, word);
}
//在以node为根的树中 添加 在word中index位置上的字符
private void addR(Node node,int index, String word) {
//递归到底情况 当到达最后一个字符的下一个空间 递归终止
if (index == word.length()) {
if (!node.isWord) {
node.isWord = true;
size++;
}
return;
}
//如果没有到达最后位置
char c = word.charAt(index);
if (node.next.get(c) == null) {
node.next.put(c, new Node());
}
addR(node.next.get(c), index + 1, word);
}
public boolean contain(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (cur.next.get(c) == null) {
return false;
}
cur = cur.next.get(c);
}
return cur.isWord;
}
public boolean containR(String word) {
return containR(root, 0, word);
}
//在以node为根的树中 查询 在word中index位置上的字符
private boolean containR(Node node, int index, String word) {
//递归到底情况
if (index == word.length()) {
return node.isWord;
}
char c = word.charAt(index);
if (node.next.get(c) == null) {
return false;
}
return containR(node.next.get(c), index + 1, word);
}23
收起
正在回答 回答被采纳积分+1
1回答
liuyubobobo
2022-07-21 04:45:29
赞,是正确的。逻辑非常清晰,相信你对递归的理解已经很深刻了。
继续加油!:)
相似问题
登录后可查看更多问答,登录/注册
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星