简体   繁体   中英

In-order traversal of BST not working correctly?

So I'm writing a program to record words from a file in an array of binary trees. The array is of size 26, each index representing a letter of the alphabet. And each element is a BST with Nodes consisting of a word and queue of line numbers (still working on that, for now it just makes a new node instead of adding a new line number to the queue)

The problem I'm running into is with tree traversal. root.toString() never prints anything to the console, but it will always print "Empty". Not too sure why this is, so any insight would help a lot!

(Please keep in mind that some code in here was just for my testing purposes and some less important things are not yet implemented completely.)

BinarySearchTree.java

import java.util.LinkedList;
import java.util.Queue;

//Binary Search Tree (BST) 
public class BinarySearchTree{
//Pointer to root Node
private Node root = null;

//Nested Node class
static class Node{

    //Node contents
    private String word;
    private Node leftChild;
    private Node rightChild;
    private Queue<String> queue = new LinkedList<String>();

    public Node(String word, String line){
        this.word = word;
        this.queue.add(line);
        this.leftChild = null;
        this.rightChild = null;
    }//End constructor

    public void setLeftChild(Node left){
        this.leftChild = left;
    }//End setLeftChild

    public void setRightChild(Node right){
        this.rightChild = right;
    }//End setRightChild

    public Node getLeftChild(){
        return this.leftChild;
    }//End getLEftChild 

    public Node getRightChild(){
        return this.rightChild;
    }//End getRightChild

    public String getWord(){
        return this.word;
    }//End getWord

    @Override
    public String toString() {
        //return this.getWord() + this.view(); //TODO fix later
        return "This is the toString for a Node";
    }//End toString

    public String dequeue() {
        return this.queue.remove();
    }//End dequeue

    public String view() {
        return this.queue.peek();
    }//End view

}//End Node class

public Node getRoot() {
    return this.root;
}//End getRoot

public void setRoot(Node n) {
    this.root = n;
}//End setRoot

// insert a node to the binary search tree
public void insert(Node root, Node newNode){

    //If no root (empty tree), newNode is root
    if(root == null) {
        setRoot(newNode);
    }
    //If root word > newNode word, move left
    else if(root.getWord().compareToIgnoreCase(newNode.getWord()) > 0){
        //No left child, insert here
        if(root.getLeftChild() == null){
            root.setLeftChild(newNode); 
        }
        //Left child exists, recurse
        else{
            insert(root.getLeftChild(),newNode);
        }

    }
    //If root word < newNode word, move right
    else if(root.getWord().compareToIgnoreCase(newNode.getWord()) < 0){
        //No right child, insert here
        if(root.getRightChild() == null){
            root.setRightChild(newNode);
        }
        //Right child exists, recurse
        else{
            insert(root.getRightChild(),newNode);
        }

    }
}//End insert

//in-order Traversal of Node
public void inOrderTraversal(Node root){
    if(root != null){
        inOrderTraversal(root.getLeftChild());
        root.toString();
        inOrderTraversal(root.getRightChild());
    }
    else
        System.out.println("Empty");

}//End inOrderTraversal

}

FileSorter.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class FileSorter {

//Create BST Array
private static BinarySearchTree[] bstArray = new BinarySearchTree[26];

public static void main(String[] args) throws FileNotFoundException {

    //Initialize the 26 BSTs
    for(int i = 0; i < 26; i++) {
        bstArray[i] = new BinarySearchTree();
    }

    //File to work with
    File file = new File("Gettysburg.txt");
    //Sort through file
    scanByLine(file);
    bstArray[1].inOrderTraversal(bstArray[1].getRoot());
    System.out.println("Complete!");

}//End main


/*
 * Below are methods for scanning a file, and also cleaning/stripping it
 * of all non alphabetic characters so they will more cleanly fit in a Node
 */

public static void scanByLine(File f) throws FileNotFoundException {
    //Keep track of line number
    int lineNum = 1;
    Scanner line = new Scanner(f);
    //While there is another line, scan it, pass to scanWords, increment lineNum
    while(line.hasNextLine()) {
        String alphaString = removeNonAlpha(line.nextLine());
        scanWords(alphaString, lineNum);
        if(!alphaString.isEmpty()) {
            lineNum++;
        }
    }
    //Close line scanner when finished
    line.close();
}//End scanByLine


public static void scanWords(String s, int line) {

    Scanner word = new Scanner(s);
    //While another word exists, scan it, place new node into array
    while(word.hasNext()) {
        String nodeWord = word.next().toLowerCase();
        String nodeLine = Integer.toString(line);
        //Add newWord to appropriate index of bstArray
        int index = (int)nodeWord.charAt(0) - 97;
        System.out.println("Creating Node.");
        //Create new Node
        BinarySearchTree.Node newNode = new BinarySearchTree.Node(nodeWord, nodeLine);
        System.out.println("Created. Adding Node with " + newNode.getWord() + " at line: " + newNode.view());
        bstArray[index].insert(bstArray[index].getRoot(), newNode);
    }
    //Close word scanner when finished
    word.close();

}//End scanWords


//Remove anything non a-z and A-Z
public static String removeNonAlpha(String s) {
    s = s.replaceAll("[^A-Za-z]", " ");
    return s;
}

}

The problem is that you call root.toString() but you don't do anything with the return value. And at the end when there are no more leaves you will just print Empty .

You should change

root.toString();

to

System.out.println(root.toString()):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM