您能否分享更多代码和输入数据,以更好地了解您要做什么?
这个关于Java 中的 Trie 数据结构的Stack Overflow 讨论可能会有所帮助:Trie 数据结构 - Java。我发现以下链接(来自答案之一)非常有用:https ://forums.oracle.com/forums/thread.jspa?messageID=8787521 。
编辑:在https://forums.oracle.com/forums/thread.jspa?messageID=8787521和Java 树数据结构的帮助下?,我创建了以下代码:
public Stack<List<Character>> createTreeAndGetAllWords() {
// Create the tree.
final Tree<Character> rootTree = new Tree<Character>('*');
final Tree<Character> cTree = rootTree.addChild(new Tree<Character>('c'));
final Tree<Character> aTree = cTree.addChild(new Tree<Character>('a'));
aTree.addChild(new Tree<Character>('r'));
aTree.addChild(new Tree<Character>('t'));
final Tree<Character> dTree = rootTree.addChild(new Tree<Character>('d'));
final Tree<Character> oTree = dTree.addChild(new Tree<Character>('o'));
oTree.addChild(new Tree<Character>('g'));
// Traverse the tree.
return getAllWords(rootTree);
}
private Stack<List<Character>> getAllWords(final Tree<Character> tree) {
final Stack<List<Character>> listStack = new Stack<List<Character>>();
for (final Tree<Character> child : tree.getChildren()) {
listStack.push(new ArrayList<Character>());
traverseSubtree(child, listStack);
}
return listStack;
}
private void traverseSubtree(final Tree<Character> tree, final Stack<List<Character>> listStack) {
final List<Character> currentWord = listStack.pop();
if (tree.hasChildren()) {
for (final Tree<Character> child : tree.getChildren()) {
final List<Character> extendedWord = new ArrayList<Character>(currentWord);
extendedWord.add(tree.getValue());
listStack.push(extendedWord);
traverseSubtree(child, listStack);
}
} else {
currentWord.add(tree.getValue());
listStack.push(currentWord);
}
}
public class Tree<T> {
private T value;
private List<Tree<T>> children;
public Tree(T value) {
this.value = value;
this.children = new ArrayList<Tree<T>>();
}
public T getValue() {
return value;
}
public boolean hasChildren() {
return children.size() > 0;
}
public Tree<T> addChild(Tree<T> child) {
children.add(child);
return child;
}
public List<Tree<T>> getChildren() {
return children;
}
}
当我调用 createTreeAndGetAllWords 时,它会返回我期望的三个字符列表:[c, a, r], [c, a, t] 和 [d, o, g]。
for (final List<Character> word : createTreeAndGetAllWords()) {
System.out.println("word = " + word);
}
干杯,弗里克