我需要构建一个程序,通过打开文件并将文件中的单词添加到 BST 来继续添加到二叉搜索树 (BST)。我已经弄清楚如何打开文件并将原始文件中的单词存储在树中,但是当我尝试打开第二个文件以继续添加到树中时,它就像我从头开始一样。如何指向下一个可用节点以便我可以继续插入到其中。
我尝试过使用插入函数,但它就像我从头开始一样,并删除了前一个文件中的所有内容。
我的节点类:
class BSTNode {
String word;
int data;
BSTNode parent;
BSTNode left;
BSTNode right;
public BSTNode(String word, int data) {
this.word = word;
this.data = data;
this.left = null;
this.right = null;
this.parent = null;
}
public BSTNode() {
}
}
我的插入功能:
void insert(BSTNode node, String word, int data) {
if (search(node, word)) {
} else {
insertNode(node, word, data);
}
}
我选择将另一个文件添加到 BST 的按钮:
} else if (evt.getSource().equals(anotherFile)) {
JFileChooser pickFile = new JFileChooser();
int dialog = pickFile.showOpenDialog(GUI.this);
if (dialog == JFileChooser.APPROVE_OPTION) {
GUI.this.file.setText(pickFile.getSelectedFile().getName());
directory.setText(pickFile.getCurrentDirectory().toString());
}
if (dialog == JFileChooser.CANCEL_OPTION) {
GUI.this.file.setText("You pressed cancel");
directory.setText("");
}
try {
Scanner scanner = new Scanner(file);
BSTFunctions bstf = new BSTFunctions();
while (scanner.hasNext()) {
bstf.insert(bstf.ROOT, scanner.next().toLowerCase().trim(), 1);
}
bstf.wordCount(bstf.ROOT);
bstf.listInOrder(bstf.ROOT);
scanner.close();
} catch (IOException e1) {
results.append("\n\u2022YOU MUST SELECT A FILE TO CONTINUE");
}
最佳答案
将 BSTFunctions bstf = new BSTFunctions();
设为 GUI
类的字段,而不是在 actionPerformed
内声明它。如果您在方法内声明它,则每次该方法运行时您都会从头开始一个新的方法。
class GUI extends JFrame {
private final BSTFunctions bstf = new BSTFunctions();
// everything else
}
关于java - 如何插入二叉搜索树上的下一个可用节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57463785/