gpt4 book ai didi

java - 将二叉树打印到文件

转载 作者:行者123 更新时间:2023-12-02 03:46:37 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com