我试图从文本文件创建决策树。从文本文件写入决策树
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;
--
--
如何做到这一点任何帮助吗?我知道我需要递归调用这个函数,但是这不太好。有任何想法吗?
节点看起来像3个构造函数是什么。另外我认为每个问题都可能导致只有2个答案或问题? – LudgerP
@路德耶是的每个问题只能有两个答案。构造函数用于创建节点 – Daniel