首页 文章

BST的有序遍历无法正常工作?

提问于
浏览
0

所以我正在编写一个程序来记录二进制树数组中的文件中的单词 . 数组大小为26,每个索引代表字母表的字母 . 每个元素都是一个BST,节点由一个单词和行号队列组成(仍在处理,现在它只是创建一个新节点,而不是向队列添加新的行号)

我遇到的问题是树遍历 . root.toString()从不向控制台打印任何东西,但它总是打印“空” . 不太清楚为什么会这样,所以任何见解都会有所帮助!

(请记住,这里的一些代码仅用于我的测试目的,一些不太重要的东西尚未完全实现 . )

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;
}

}

1 回答

  • 0

    问题是你调用 root.toString() 但是你没有对返回值做任何事情 . 最后,当没有叶子时,你将只打印空 .

    你应该改变

    root.toString();
    

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

相关问题