【问题标题】:number of nodes in trie nodetrie节点中的节点数
【发布时间】:2022-01-02 09:49:57
【问题描述】:

在这里,我创建了一个类 Trie 和 TrieNode,它在 Java 中实现了 Trie 数据结构。 我的任务是编写一个名为 size() [return type int] 的方法来返回 Trie 中的节点数。

class Trie {

    private TrieNode root;

    /////////////////////
    // TrieNode class
    class TrieNode {
        public char c;
        public boolean isWord;
        public TrieNode[] children;

        public TrieNode(char c) {
            this.c = c;
            isWord = false;
            children = new TrieNode[26];
        }
    }

    public Trie() {
        root = new TrieNode('\0');
    }

    public boolean isPrefix(String word) {
        return getNode(word) != null;
    }

    public void insert(String word) {
        TrieNode curr = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (curr.children[c - 'A'] == null)
                curr.children[c - 'A'] = new TrieNode(c);
            curr = curr.children[c - 'A'];
        }
        curr.isWord = true;
    }

    // Helper
    private TrieNode getNode(String word) {
        TrieNode curr = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (curr.children[c - 'A'] == null)
                return null;
            curr = curr.children[c - 'A'];
        }
        return curr;
    }

我一直在尝试获取 Trie 中的节点数,我在想的是:

    public int size() {
        return size(root);
    }

    private int size(TrieNode root) {

        for (int i = 0; i < root.children.length; i++) {
            if (root.children[i] != null) {
                if (root.isWord)
                return 1;
                else
                    return 1 + size(root.children[i]);
            }
        }
        return 0;
    }

但这是不对的。有什么想法吗?

【问题讨论】:

    标签: java arrays data-structures trie


    【解决方案1】:

    这很简单Depth-first search:

    public static int size(TrieNode node) {
        if(node == null)
            return 0;
        
        int total = 1;
        
        for(TreeNode child : node.children)
            total += size(child);
        
        return total;
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-18
      • 2022-01-08
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 2016-03-04
      相关资源
      最近更新 更多