I'm having trouble writing code to save binary trees that are created by my program. I'm trying to save the tree to a file by trying to use preOrder traversal and writing the data that way. But so far nothing gets written to the text file.
I'm supposed to write the program so it stores the data like this:
(100,2) (200,L) (400,0) (300,R) (500,0)
The first number in the pair represents the node and the second letter/number represents how many children/which side the child is.
So far I have the following code, but have not gotten results from this. I believe I'm not properly passing the data or traversing the tree the right way.
I would appreciate it if I could get more help/explanation on the process of doing this or if someone could comment on the code I have so far. Thank you.
Code in my "main" class:
t.saveTree("savedtree.txt");
Code in my "BinaryTree" class:
public void saveTree(String s)
{
if(!isEmpty())
root.filePreOrder();
}
Code in my "BinaryNode" class:
void filePreOrder()
{
BufferedWriter bufferedWriter = null;
try
{
bufferedWriter = new BufferedWriter(new FileWriter("savedtree.txt"));
bufferedWriter.write("(" + data + ",");
if(left != null && right != null)
{
int c = 2;
bufferedWriter.write(c + ")");
}
else if(left == null && right == null)
{
int c = 0;
bufferedWriter.write(c + ")");
}
left.filePreOrder();
bufferedWriter.write("(" + data + ",");
if(left != null && right == null)
{
char c = 'L';
bufferedWriter.write(c + ')');
}
}
catch (Exception e)
{
if (e instanceof FileNotFoundException)
System.out.println("File not found, terminating..");
System.exit(0);
}
}