我有一个enlish字典,它是一个包含enlish单词列表(一行单词)的文件。
我必须在像通用树这样的数据结构中呈现这个字典。
所以我想要这样的东西:

Dictionary = [
    TA: Tree that rapresent words that starts with 'a':
                .a
           / | \  ... \
          .a .b   ... .z
          /|\         /|\
                ...

    TB: Tree that rapresent words that starts with 'b':
                .b
           / | \  ... \
          .a .b   ... .z
          /|\         /|\
                ...

                ...

    TZ: Tree that rapresent words that starts with 'bz':
                .z
           / | \  ... \
          .a .b   ... .z
          /|\         /|\
                ...
]


根与节点之间的路径是一个单词(或一个单词)。

做这个的最好方式是什么?

现在,我创建了一个这样的类Node:

public class Node {
    private static char ch;
    private static int count;

    Node(char ch, int count) {
        this.ch = ch;
        this.count = count;
    }

    Node(char ch) {
        this.ch = ch;
    }

    Node(int count) {
        this.count = count;
    }

    public static char getChar() {
        return ch;
    }

    public static int getCount() {
        return count;
    }

    public static int incrementCounter() {
        return count++;
    }

    public String toString() {
        String s = "";
        s += "'" + ch + "' (" + count + ") ";
        return s;
    }
}


然后我正在考虑做类似的事情:

public class GenericTreeNode<Node> {

    public Node data;
    public List<GenericTreeNode<Node>> children;

    ...
}


但是以这种方式,我将生成TA,TB,...,TZ等单个通用树,而不是整个Dictionary。
或不?

有人能帮我吗?

谢谢

最佳答案

我认为您不需要为此目的的GenericTreeNode类。您可以扩展您的Node类,使其包括以下子项。

public class Node {

    private char mChar;
    private Set<Node> mChildren;
    //declare other variables you need here

    public Node(char c) {
        mChar = c;
        mChildren = new HashSet<Node>();
    }

    public Node addChild(Node node) {
        mChildren.add(node);
        return node;
    }

    public char getChar() {
        return mChar;
    }
}


一旦创建了这样的Node类,就可以如下生成树结构。

public void buildTree() {
    //use any non alphabet character for root node.
    //used '*' here.
    Node root = new Node('*');
    //add child 'a'
    Node a = new Node('a');
    root.addChild(a);

    //add child 'ab'
    a.addChild(new Node('b'));

    //add child 'efg'
    root.addChild(new Node('e')).addChild(new Node('f')).addChild(new Node('g'));
}


希望您能掌握主要思想。这是要创建一个具有值的Node类,该类还包含一组相同类型的Node子级。一旦实现了这一点,就可以生成任何深度的树结构。

注意:您已经在private static char ch;类中声明了Node。您不应将其声明为静态。如果是这样,您将无法在不同节点中为变量ch分配不同的值

10-07 19:43
查看更多