写入文件。 (二叉搜索树)

发布于 2024-08-29 12:58:42 字数 539 浏览 0 评论 0原文

我不知道如何编写二叉搜索树以递归方式归档。我在 Tree 类中打开一个 BufferWriter,其中包含要写入的文件。然后,我将 BufferWriter 发送到 Node 类以按顺序遍历树并写入文件。但这不起作用。

public void write(String filePath)
{
  if(root != null) {
    try {
      BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
      root.write(out);
    } catch (IOException e) {
    }
  }
}

public void write(BufferedWriter out)
{
    if (this.getLeft() != null) this.getLeft().write(out);
    out.write(this.data());
    if (this.getRight() != null) this.getRight().write(out);
}

I can't figure out how to write a Binary Search Tree to file recursively. I open a BufferWriter with the file to wrtie too, in the Tree class. I then send the BufferWriter to the Node class to traverse the tree inorder and write to file. But it doesn't work.

public void write(String filePath)
{
  if(root != null) {
    try {
      BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
      root.write(out);
    } catch (IOException e) {
    }
  }
}

public void write(BufferedWriter out)
{
    if (this.getLeft() != null) this.getLeft().write(out);
    out.write(this.data());
    if (this.getRight() != null) this.getRight().write(out);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你穿错了嫁妆 2024-09-05 12:58:42

看起来没那么糟糕!可能是您在完成后缺少 BufferedWriter 上的 close() 吗?如果没有 close,文件可能无法正确写入。

That doesn't look so bad! Could it be you're just missing the close() on your BufferedWriter when you're done? The file will likely not be written correctly if there's no close.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文