Click here to Skip to main content
14,975,098 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to write a binary Search tree to a text file in sorted order, my write method is in my BST class. When I print out the BST in Order Tranversal it works perfectly. When I try to write it to a text file it works but the current node being written inserts null to the text file instead of the node

public void write(Node focusNode)
        // Creates a FileWriter
        FileWriter fileName = new FileWriter("Binary Search Tree.txt");

        // Creates a BufferedWriter
        BufferedWriter  bw = new BufferedWriter(fileName);
        if (focusNode != null) {
            bw.write(focusNode.leftChild+"\n"); //adds the  left node

            bw.write(focusNode+"\n");//add the current node

            bw.write(focusNode.rightChild+"\n"); // add the right node
            System.out.print("Your binary search tree is empty");
    catch(Exception ex) {
        System.out.print("An error occured try again ");

What I have tried:

I've tried creating a copy of focusNode
and writing the copy,but when I write it I still get null
Updated 22-May-21 11:25am
Gerry Schmitz 22-May-21 17:24pm
Maybe you have to check left and right children for null.

1 solution

The first thing to notice is that when you construct a FileWriter instance with just a string parameter, it always overwrites any existing file. So if you want to have more than one node in your file at any time, you either need to use the overload that accepts a string and a bool to allow you to append, or you need to move the writer outside your write method and pass it as a parameter instead.

And that's probably your problem, since by definition, the last node you process will always have null left and right nodes ...

I'd also recommend that you either prefix your data: "N:" for the node, "L:" and "R:" for the subnodes, or combine them onto the same line to make the file more readable and human editable. As it is, you have to count lines to work out what a bit of data is ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900