If in the writeToFile
method you mention you are always opening, writing to and closing the same file, you are basically telling it to overwrite everything each time you print, resulting in the file containing only one value when the program terminates.
You can overcome this by opening the file in append mode if you insist on using your function that way, by opening the file like this (notice the true argument):
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
However, opening and closing the file for each write is really inefficient, so a better way to do this is as follows:
Assuming you are calling your method from main, you could do something like this if you print one element at a time:
private static BufferedWriter bw;
public static void main(String[] args) {
File file = new File("/your/file/path/<filename>");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
postOrderTrav(node);
bw.close();
}
and in your method you would have:
public static void postOrderTrav(TreeNode node){
if(node != null){
postOrderTrav(node.getLeft());
postOrderTrav(node.getRight());
System.out.print(node.getVal() + " ");
bw.write(node.getVal() + " ");
}
}
Have a look here about information for printing to a file. You can either print directly to the file when printing to output or you can store the result in a data structure (or String) and print it at the end.