我想问这个问题,但在我目前的驱动程序,我已经打印出了一个使用迭代器到文本文件的树的前序成功。我不知道如何打印我的递归方法,因为我不能把它们放到println语句中,因为它们是void方法。我知道我应该让这个方法把writer作为一个参数,但不知道怎么做(driver的最后几个println语句)。感谢您的帮助!
司机:
package driver;
import java.io.*;
import java.util.*;
public class Driver {
private static Scanner file;
static PrintWriter outputFilePrinter;
static Scanner inputFileScanner;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile; //Declaring scanner obj
PrintWriter printWriter = new PrintWriter("output.txt"); //Text file where results are printed to
inFile = new Scanner(new File("input.txt")); //Text file where student names and associated number are read from
BinarySearchTreeInterface<String> aTree = new BinarySearchTree<>() {}; //Giving access to BinarySearchTree methods
while (inFile.hasNext()) { //Scans input file
String name = inFile.nextLine(); //Assigns contents to string obj
aTree.add(name); //Add string to a tree
} //End while
Iterator<String> traverse = aTree.getPreorderIterator(); //Using iterator to print tree in an "postorder" fashion
while (traverse.hasNext())
printWriter.println(traverse.next()); //Prints tree
System.out.println("Postorder Recrusive: ");
aTree.postorderTraverse();
System.out.println("");
System.out.println("Inorder Recursive: ");
aTree.inorderTraverse();
printWriter.close(); //Closes file
} //End Main
} //End Driver
我正在尝试打印的递归方法:
public void inorderTraverse() {
inorderTraverse(root);
}
public void inorderTraverse(BinaryNode<T> node) {
if (node != null) {
inorderTraverse(node.getLeftChild());
System.out.println(node.getData());
inorderTraverse(node.getRightChild());
}
}
public void postorderTraverse() {
postorderTraverse(root);
}
public void postorderTraverse(BinaryNode<T> node) {
if (node != null) {
postorderTraverse(node.getLeftChild());
postorderTraverse(node.getRightChild());
System.out.println(node.getData());
}
}
1条答案
按热度按时间5kgi1eie1#
您可以将遍历代码更改为
甚至
把第二个变量称为: