I have a method that is supposed to print a binary tree to a file. This is it:
public void writeFile(Node mainNode)
{
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
try
{
outputStream = new FileOutputStream("BinaryTree.txt");
printWriter = new PrintWriter(outputStream);
while(mainNode != null)
{
writeFile(mainNode.leftChild);
printWriter.print(mainNode);
writeFile(mainNode.rightChild);
}
printWriter.close();
}catch(IOException e)
{
System.out.println("An error occured");
printWriter.close();
}
}
The problem is that it seems to eternally loop as it's not finding the end of the tree. Is there anything I can try.
Here's the Node class too.
class Node
{
int id;
int grade;
String name;
Node leftChild;
Node rightChild;
Node(int id, int grade, String name )
{
this.id = id;
this.grade = grade;
this.name = name;
}
public String toString()
{
return name + " has a grade of " + grade + " and their ID is " + id;
}
}