You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Trie类的remove方法改造为无需传节点的TrieNode成员方法

字典树删除方法从Trie类迁移到TrieNode类的实现方案

你已经实现的Trie类入口方法无需调整,改造核心是把原静态方法中所有对入参root的操作,替换为成员方法中对当前实例this的操作即可,具体实现如下:


改造后TrieNode类完整参考代码

public class TrieNode {
    // 原有成员属性无需调整
    boolean isEndOfWord;
    TrieNode[] children = new TrieNode[26];

    // 原有辅助isEmpty方法改为TrieNode成员方法即可
    private boolean isEmpty() {
        for (int i = 0; i < 26; i++) {
            if (children[i] != null) {
                return false;
            }
        }
        return true;
    }

    // 改造后的删除成员方法,无需传入当前节点参数
    public TrieNode remove(String key, int depth) {
        // 已处理到目标key的最后一个字符
        if (depth == key.length()) {
            // 取消当前节点的单词结束标记
            if (this.isEndOfWord) {
                this.isEndOfWord = false;
            }
            // 当前节点无任何子节点,返回null表示该节点可直接删除
            if (this.isEmpty()) {
                return null;
            }
            return this;
        }

        // 递归处理对应位置的子节点
        int index = key.charAt(depth) - 'a';
        // 子节点为空时无需调用删除方法,直接赋值null即可
        if (this.children[index] != null) {
            this.children[index] = this.children[index].remove(key, depth + 1);
        }

        // 当前节点无任何子节点,且不是其他单词的结束节点,返回null表示可删除
        if (this.isEmpty() && !this.isEndOfWord) {
            return null;
        }
        return this;
    }
}

和原静态方法的核心差异

  • 移除了原静态方法的第一个TrieNode root入参,所有对root的操作替换为对当前实例this的操作
  • 原方法开头的root == null判断无需保留,因为只有实例化的TrieNode对象才能调用成员方法,递归调用子节点前提前判空即可,逻辑和原实现完全等价
  • 原有删除逻辑、前缀判断、节点回收规则完全不变,不会影响原有功能的运行结果

内容的提问来源于stack exchange,提问作者JamesR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:27:04