我有一个需要构建的程序,我通过打开一个文件并将文件中的单词添加到 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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句