Trie add和contain 递归写法

来源:2-2 Trie字典树基础

星岳神话

2022-07-16 21:29:23

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);
}


写回答

1回答

liuyubobobo

2022-07-21

赞,是正确的。逻辑非常清晰,相信你对递归的理解已经很深刻了。


继续加油!:)

0

算法与数据结构

波波老师5年集大成之作,算法与数据结构系统学习,考试、面试、竞赛通用

2610 学习 · 1087 问题

查看课程