【发布时间】:2017-11-09 16:57:23
【问题描述】:
我试图打印一个正确排序的 Radix Trie,但是当我尝试这样做时,它与 DFS 一起使用,但单个字母打印在错误的位置......我做错了什么?我在递归上做错了还是我需要另一个我缺少的条件?
Ex:
0692
072755
0
1008
1076
10
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Trie {
static class TrieNode {
TrieNode[] children = new TrieNode[128];
boolean leaf;
}
public static void insertString(TrieNode rootNode, String s) {
TrieNode root = rootNode;
for (char ch : s.toCharArray()) {
TrieNode next = root.children[ch];
if (next == null)
root.children[ch] = next = new TrieNode();
root = next;
}
root.leaf = true;
}
public static void printSorted(TrieNode node, String s) {
for (char ch = 0; ch < node.children.length; ch++) {
TrieNode child = node.children[ch];
if (child != null)
printSorted(child, s + ch);
}
if (node.leaf) {
System.out.println(s);
}
}
public static void main(String[] args) throws IOException {
TrieNode root = new TrieNode();
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
String line = null;
while ((line = br.readLine()) != null) {
insertString(root, line);
line = null;
}
printSorted(root, "");
}
}
【问题讨论】: