繁体   English   中英

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

[英]In-order traversal of BST not working correctly?

因此,我正在编写一个程序来记录二进制树数组中文件中的单词。 该数组的大小为26,每个索引代表一个字母。 每个元素都是一个BST,其Nodes由一个单词和行号队列组成(仍在起作用,目前,它只是创建一个新节点,而不是向队列中添加新的行号)

我遇到的问题是遍历树。 root.toString()永远不会在控制台上打印任何内容,但始终会打印“ Empty”。 不太清楚为什么会这样,所以任何见解都会有很大帮助!

(请记住,这里的一些代码仅用于我的测试目的,而一些次要的事情尚未完全实现。)

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

}

问题是您调用root.toString()但对返回值不做任何事情。 最后,当没有更多的叶子时,您将只打印Empty

你应该改变

root.toString();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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