java - 如何插入二叉搜索树上的下一个可用节点?

标签 java user-interface binary-search-tree nodes

我需要构建一个程序,通过打开文件并将文件中的单词添加到 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/

相关文章:

Java - 从文件中读取错误的字符

java - 如何在不访问更大类型的情况下缩放 Int64 值?

java - Mockito 可以根据方法调用时的值来验证参数吗?

java - 仅删除文本区域中的选定文本

带 GUI 的 Java 测验

c - 删除二叉搜索树根节点的问题

python - 从列表创建一个完整的二叉搜索树

java - 使用以 BlockingQueue<Runnable> 作为参数的构造函数创建的 ThreadPoolExecutor 如何将 Callables 排入队列?

c - 将新节点插入二叉树并返回其头指针

web - 为什么登录字段大多是右对齐的?