Ai
2 Star 0 Fork 0

CS-IMIS-23/20172311hai

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
DecisionTree.java 2.97 KB
一键复制 编辑 原始数据 按行查看 历史
package week8;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
/*
决策树类的构建
*/
public class DecisionTree {
private LinkedBinaryTree<String> tree;
/*
使用文件中的内容初始化二叉树的关联关系
这个地方需要学习的是树的链表存储的构建方式: 在链表树的存储过程中可以首先添加结点,然后根据关联关系表来添加关联
或者在构建tree结点的同时设置连边关联
*/
public DecisionTree(String filename) throws FileNotFoundException {
File inputFile = new File(filename);
Scanner scan = new Scanner(inputFile);
int numberNodes = scan.nextInt();// 整型读出
scan.nextLine();
int root = 0;
int left, right;
// 用户存储二叉树的列表
List<LinkedBinaryTree<String>> nodes = new java.util.ArrayList<LinkedBinaryTree<String>>();
// 将当前的元素包装之后放到树里面
for (int i = 0; i < numberNodes; i++)
nodes.add(i, new LinkedBinaryTree<String>(scan.nextLine()));
// 一行一行的读数据 给每一个二叉树分配自己的位置
while (scan.hasNext()) {
root = scan.nextInt();
left = scan.nextInt();
right = scan.nextInt();
scan.nextLine();
// 根据索引组合树
nodes.set(
root,
new LinkedBinaryTree<String>((nodes.get(root))
.getRootElement(), nodes.get(left), nodes
.get(right)));
}
// 最后将根结点对象引用指向tree
tree = nodes.get(root);
}
//Follows the decision tree based on user responses.
public void evaluate() {
LinkedBinaryTree<String> current = tree;
Scanner scan = new Scanner(System.in);
while (current.size() > 1) {
System.out.println(current.getRootElement());
if (scan.nextLine().equalsIgnoreCase("N"))
current = current.getLeft();
else
current = current.getRight();
}
System.out.println("Output the Judge Result :"+current.getRootElement());
}
//返回背部疼痛诊断器中决策树的叶子节点个数
public int CountLeaf(BinaryTreeNode tree){
if (tree!=null){
if (tree.getLeft()==null&&tree.getRight()==null)
return 1;
else
return CountLeaf(tree.getLeft())+CountLeaf(tree.getRight());
}
else
return 0;
}
//返回LinkedBinaryTree<String> tree
public LinkedBinaryTree<String> getTree(){
return tree;
}
//递归方法实现层序输出
public void toLevelString1(){
tree.toLevelString1();
}
//非递归方法实现层序输出
public void toLevelString2(){
tree.toLevelString2();
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/CS-IMIS-23/20172311hai.git
git@gitee.com:CS-IMIS-23/20172311hai.git
CS-IMIS-23
20172311hai
20172311hai
master

搜索帮助