gpt4 book ai didi

java - 从文本文件写入决策树

转载 作者:行者123 更新时间:2023-12-01 13:05:09 26 4
gpt4 key购买 nike

我正在尝试从文本文件创建决策树。

public static BTNode<String> fileToTree (String fileName) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(fileName));
BTNode<String> node = new BTNode("", null, null);
BTNode<String> answer = fileToTreeHelper(node, file);
file.close();
return answer;
}
public static BTNode<String> fileToTreeHelper (BTNode<String> node, Scanner fileScanner) throws IOException {
String line;

if(node == null){
node = new BTNode<String>(fileScanner.nextLine(), null, null);
fileToTreeHelper(node, fileScanner);
}else{
if(fileScanner.hasNext()){
if(node.isLeaf()){
node.setData(fileScanner.nextLine());
}
if(node.getLeft() == null) {
line = fileScanner.nextLine();
if(line.contains("?")) {
node.setLeft(new BTNode<String>(line, null, null));
}
if(line.contains(";")) {
node.setLeft(new BTNode<>(line,null, null));
node.setRight(new BTNode<>(fileScanner.nextLine(),null, null));
}
}

if(node.getRight() == null) {
line = fileScanner.nextLine();
if(line.contains("?")) {
node.setRight(new BTNode<String>(line, null, null));
}
if(line.contains(";")) {
node.getLeft().setLeft(new BTNode<>(line,null, null));
node.getLeft().setRight(new BTNode<>(fileScanner.nextLine(),null, null));
node.setRight(new BTNode<String>(line, null, null));
fileToTreeHelper(node.getRight(), fileScanner);
}
}
}
}
return node;
}

这是我到目前为止所拥有的;当我运行它时,决策树应该看起来像这样:

Are you a mammal?
Are you bigger than a cat?
Kangaroo;
Mouse;
Do you live underwater?
Trout;
Robin;

但到目前为止我得到的只是:

Are you a mammal?
Are you bigger than a cat?
Kangaroo;
--
--

关于如何执行此操作有任何帮助吗?我知道我需要递归调用这个函数,但这效果不太好。有什么想法吗?

最佳答案

我认为你的算法很困惑,它应该是这样的:

    Node node = new Node(fileScanner.nextLine())
// If the node is a question, it should have 2 subnodes with the answers / nested questions.
if(line.contains("?")){
node.setLeft(fileToTreeHelper(...));
// If there is an option that has only 1 answer, then this should have an if that
// checks if there is a ";" and then create the node or set it as null.
node.setRight(fileToTreeHelper(...));
}
// If it is not a question, then it's just an answer to a previous question and returns.
return node;

关于java - 从文本文件写入决策树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23321508/

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