java - 将二叉树打印到文件

标签 java save binary-tree

我有一个方法应该将二叉树打印到文件中。就是这样:

public void writeFile(Node mainNode)
{
    FileOutputStream outputStream = null;
    PrintWriter printWriter = null;

    try
    {

        outputStream = new FileOutputStream("BinaryTree.txt");
        printWriter = new PrintWriter(outputStream); 


        while(mainNode != null)
        {
             writeFile(mainNode.leftChild);
             printWriter.print(mainNode);
             writeFile(mainNode.rightChild); 

        }

        printWriter.close();

  }catch(IOException e)
  {
     System.out.println("An error occured");
      printWriter.close();
  }

}

问题是它似乎永远循环,因为它没有找到树的末端。有什么我可以尝试的吗?

这也是 Node 类。

class Node
{
int id;
int grade;
String name;

Node leftChild;
Node rightChild;


Node(int id, int grade, String name )
{
    this.id = id;
    this.grade = grade;
    this.name = name;
}


public String toString()
{
    return name + " has a grade of " + grade + " and their ID is " + id;
}
}

最佳答案

您预计这个循环如何结束:

while(mainNode != null) {
    // never change mainNode
}

您需要将 PrintWriter 作为参数传递给函数,以便所有递归调用写入(追加)到同一文件。然后提供一个停止的基本情况:

public void writeFile(Node mainNode, PrintWriter w)
{
    if (mainNode == null)  // base case to stop recursion  
        return;
    top_call = false;  // Flag needed later
    if (w == null) {
        outputStream = new FileOutputStream("BinaryTree.txt");
        w = new PrintWriter(outputStream); 
        top_call = true;  // mark highest entry point to know when to close writer
    }
    writeFile(mainNode.leftChild, w);
    w.print(mainNode);
    writeFile(mainNode.rightChild, w);

    if (top_call)  // don't close writer in recursive calls
        w.close();
}

关于java - 将二叉树打印到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36241805/

相关文章:

java - 使用 UTF-16 编码和 BOM 在 Ant 中编写文本文件

c# - 将 DataGridView 导出到 CSV 文本文件

Java 使用新名称保存文件时出现问题

macos - 保存文件时出现权限错误(沙盒)

c++ - 在 cpp 中返回一对时出错

c++ - 二叉树搜索和跟踪

Java 为 ( x : y) execution

java - Mojarra Java EE 5/6 兼容性

Java : BST - removing a node with no children doesn't work

java - Java 中的点数组排序