【问题标题】:How can I make my traversal methods for Binary Search Trees return the string in Java?如何使二叉搜索树的遍历方法返回 Java 中的字符串?
【发布时间】:2021-12-18 03:48:56
【问题描述】:

我创建了两个 void 方法,它们打印出 inorder 遍历和二叉搜索树的镜像广度优先遍历。但是,我只让他们打印出结果,我现在想使用缓冲写入器将结果写入文本文件。最好的方法是什么?

    public void inorder(BSTNode<T> p) {
        if (p != null) {
            inorder(p.left);
            System.out.print(p.el + " ");
            inorder(p.right);
        }
    }

    public void mirrorBreadthFirst() {
        BSTNode<T> p = root;
        Queue<BSTNode<T>> queue = new Queue<BSTNode<T>>();
        if (p != null) {
            queue.enqueue(p);
            while (!queue.isEmpty()) {
                p = queue.dequeue();
                System.out.print(p.el + " ");
                //opposite of breadth first (reading from right to left):
                if (p.right != null)        
                    queue.enqueue(p.right);
                if (p.left != null)
                    queue.enqueue(p.left);
            }
    }

这是我的两种方法(注意:p.el 是节点 p 的元素)。

我尝试将 (p.el) 的值存储在 ArrayList 中,然后使用 toString 返回它,但是当我尝试在我的 main 方法中使用 System.out.println(mirrorBreadthFirst()); 时它不起作用。

【问题讨论】:

    标签: java data-structures methods return binary-search-tree


    【解决方案1】:

    以下是使用BufferedWriter 类写入文件的方法。您可以使用它来代替(或除此之外)使用System.out 登录到控制台:

    public static void main(final String[] args) throws Exception
    {
        final String s = "This is the data in the output file";
    
        try (final BufferedWriter output = new BufferedWriter(new FileWriter("C:/output.txt"));)
        {
            output.write(s);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多