这是基于预购的决策树 这里是树的填充代码
Position<Integer> n0 = tree.addRoot(0);
Position<Integer> n1 = tree.insertLeft(n0, 1);
Position<Integer> n3 = tree.insertRight(n0, 3);
Position<Integer> n2 = tree.insertLeft(n1, 2);
Position<Integer> r2 = tree.insertRight(n1, 1);
Position<Integer> r0 = tree.insertLeft(n2, 2);
Position<Integer> r1 = tree.insertRight(n2, 9);
Position<Integer> r3 = tree.insertLeft(n3, 2);
Position<Integer> r4 = tree.insertRight(n3, 8);
Position<Integer> r5 = tree.insertLeft(r4, 4);
Position<Integer> r6 = tree.insertRight(r4, 5);
下面是我的代码,我尝试将树划分为左子树和右子树,并将它们放入一个数组列表中。但是对于每个部分,还需要考虑这个子树的高度作为循环数
//calculate height of heap
int a = (int) Math.floor(Math.log(tree.size()) / Math.log(2));
List<String> input1 = new ArrayList<String>();
List<String> input2 = new ArrayList<String>();
Position<Integer> p1 = tree.root();
Position<Integer> p2 = tree.root();
//3 is the height of left side heap
for(int i=0;i<3;i++)
{
//left hand-side
if (tree.hasLeft(p1) == true && tree.hasLeft(tree.left(p1))==true)
{
input1.add("Y->Q"+tree.left(p1).element());
if (tree.hasLeft(tree.right(p1))==true)
{
input1.add("N->Q"+tree.right(p1).element());
}
else
{
input1.add("N->R"+tree.right(p1).element());
}
}
else
{
input1.add("Y->R"+tree.left(p1).element());
input1.add("N->R"+tree.right(p1).element());
}
p1 = tree.left(p1);
}
//3 is the heap height of right
for(int n=0;n<3;n++)
{
//right hand-side
if (tree.hasRight(p2) == true && tree.hasLeft(tree.right(p2))==true)
{
input2.add("N->Q"+tree.right(p2).element());
}
else
{
input2.add("Y->R"+tree.left(p2).element());
input2.add("N->R"+tree.right(p2).element());
}
p2 = tree.right(p2);
}
但输出是
array input1: [Y->Q1, N->Q3, Y->Q2, N->R1, Y->R2, N->R9]
array input2: [N->Q3, N->Q8, Y->R4, N->R5]
预期的结果应该是
array input1: [Y->Q1, N->Q3, Y->Q2, N->R1, Y->R2, N->R9]
array input2: [Y->R2, N->Q8, Y->R4, N->R5]
我想要的最终结果是
Y->Q1:
Y->Q2:
Y->R2
N->R9
N->R1
N->Q3:
Y->R2
N->Q8
Y->R4
N->R5
我知道它可以使用 SringBuilder 为每个子决策使用 3 个空格来完成缩进。但不知道该怎么做,在此之前,需要修复'array input2'
新代码在这里
public static void printDecisionTree(BinaryTree<Integer> tree) {
Position<Integer> root = tree.root();
boolean isLeft =true;
StringBuilder output = new StringBuilder();
String LS = System.getProperty("line.separator");
if(tree.hasLeft(root) || tree.hasRight(root)){
if(isLeft)
output.append("Y->Q"+root.element()+LS);
else
output.append("N->Q"+root.element()+LS);
}
else{
if(isLeft)
output.append("Y->R"+root.element()+LS);
else
output.append("N->R"+root.element()+LS);
}
if (tree.hasLeft(root)&& isLeft==true){
printDecisionTree(tree);
}
if (tree.hasRight(root)&& isLeft==false){
printDecisionTree(tree);
}
System.out.print(output);
}