gpt4 book ai didi

java - 如何使用文本文件递归制作树?

转载 作者:行者123 更新时间:2023-12-05 06:36:57 24 4
gpt4 key购买 nike

我有一个包含以下内容的文本文件:

1Would you like Food or Drink? Enter either y for option one or n for the other.
1Would you like Hot food y/n?
Tomato Soup
Chicken salad
1Would you like a Fizzy drink? y/n?
Pepsi
Water

以“1”开头的句子表示一个问题。这些线是为树预先排序的。我想使用缓冲阅读器递归地生成一个方法来配合它。我希望树看起来像下面这样:

Would you like Food or Drink? Enter either y for option one or n for the other.
Would you like Hot food y/n?
Tomato Soup
Chicken Salad
Would you like a Fizzy drink? y/n?
Pepsi
Water

我正在努力制定该方法,我相信基本情况是新行是答案而不是问题。到目前为止我有这个:

public static void fromPreOrder(BufferedReader br) throws IOException {
String line = br.readLine();
if (!line.startsWith("*")) {
return;
}
TreeNode fromPreOrderTree = new TreeNode(line);
line = br.readLine();
if (line.startsWith("*"));
fromPreOrderTree.left = new TreeNode(line);
fromPreOrder(br);

}

但它没有按预期工作。

最佳答案

代码

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class TreeNode {
TreeNode left;
TreeNode right;
String text;
}

public class SO {

public static void main(final String... args) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
TreeNode node = readNode(br);
}
}

public static TreeNode readNode(BufferedReader reader) throws IOException {
String text = reader.readLine();
if (text.charAt(0) == '1') {
TreeNode node = new TreeNode();
node.text = text.substring(1);
node.left = readNode(reader);
node.right = readNode(reader);
return node;
} else {
TreeNode node = new TreeNode();
node.text = text;
return node;
}
}
}

说明

对于每个节点,如果它以 1 开头,我们读取它和 2 个子节点,否则我们只读取当前节点。

关于java - 如何使用文本文件递归制作树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612280/

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