Search code examples
javafile-iobinary-search-tree

How to write a BST to a text file


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)
{
    
    try{
        // 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
        }
        else{
            System.out.print("Your binary search tree is empty");
        }
        bw.close();
    }   
    catch(Exception ex) {
        System.out.print("An error occured try again ");
    }
}

Solution

  • Assuming the problem is the null prints, this happens because you're printing the left and right children without checking if they exist first.

    Two ways to correct it: either to add a nullity check before the print, or count on the recursive call to do it for you.

    Another problem:

    You keep opening the file and overriding it's content! You should open it only once, and then call a recursive function and pass into it bw so that all the calls will write into the same file without overriding the content that the other calls wrote

    The code should look something like this (not tested!):

    public void writeTree(Node root) {
        try {
            FileWriter fileName = new FileWriter("Binary Search Tree.txt"); 
            BufferedWriter bw = new BufferedWriter(fileName);
            write(root, bw);  
            bw.close();  
        }   
        catch(Exception ex) {
            System.out.print("An error occured try again ");
        }    
    }
    
    public void write(Node focusNode, BufferedWriter bw) {   
        if (focusNode == null) { 
            return;
        }
        write(focusNode.leftChild, bw); // calls recursively
        bw.write(focusNode+"\n");
        write(focusNode.rightChild, bw); // calls recursively
    }