我正在尝试编写递归教科书中的一个示例,其中有此方法可以从我的二进制搜索树中打印键和值的列表:
public void listBindings(printstream out) {
if (root != null) {
root.left.listBindings(out);
out.println(root.key + " = " + root.value);
root.right.listBindings(out);
}
}
我需要使用PrintWriter创建一个getWriter()来从BST中打印这些键和绑定的列表。我该怎么办?
我尝试了以下方法:
public String printListBindings() {
if (root != null) {
StringBuilder sb = new StringBuilder();
sb.append(root.left);
sb.append(root.key + " = " + root.value);
sb.append(root.right);
}
return printListBindings(); // this recurses to a stackoverflow
}
public String getWriter(listBindings (out)) {
PrintWriter pw = new PrintWriter(listBindings(out),true);
return pw.toString();
}
public String printBindings(ArrayList<String> bindings) {
if (root != null) {
String leftNode = root.left.listBindings(key); // I think it is supposed to recurse?
String rightNode = root.right.key; // or maybe this way?
bindings.add(root.key);
}
return bindings.toString();
}
public void writeBindings(String fileName) {
PrintWriter outputWriter = new PrintWriter(out);
ArrayList<String> bindings = new ArrayList<String> ();
for (String binding : bindings) {
outputWriter.write(binding);
outputWriter.newLine();
}
outputWriter.close();
}