我正在尝试为决策树程序编写节点类。我不确定如何创建一个递归调用自身直到到达所有叶节点的构造函数,以及我需要哪些辅助方法。这是我目前所拥有的。
package DecisionTree;
public class DecisionTNode {
Instance[] a;
double testValue;
DTNode left, right;
public static DTNode sortedArrayToBST(Instance[] num, int start, int end) {
if (start > end) {
return null;
}
int mid = start + (end-start)/2;
DTNode root = new DTNode(num.length, num);
root.left = sortedArrayToBST(num, start, mid-1);
root.right = sortedArrayToBST(num, mid+1, end);
return root;
}
}
最佳答案
您的sortedArrayToBST
将递归地创建所有节点。
你不需要递归构造函数,你只需要一个非常简单的构造函数,将 testValue
的值作为参数并设置它。
private DTNode(double data)
{
testValue = data;
}
并将调用更改为:
DTNode root = new DTNode(num[mid].getAttribute());
好吧,这是假设您希望您的类(class)与现在差不多。您可能希望拥有一个 Instance
成员并改为设置它(或其他任何内容),但代码看起来非常相似。
理想的情况是使用 generics , 但一次一步。
你会在 DecisionTree
中调用它(你可能会添加一个 DTNode root
成员),比如:
root = sortedArrayToBST(instances, 0, instances.length);
如果您想要一个递归构造函数,您可能想要用它替换您的sortedArrayToBST
函数 - 它们看起来非常相似,只需删除DTNode root = ...
行并按照上面的建议设置成员变量的值,然后删除 return null
if 语句,而不是进行会触发它的调用。
public DTNode(Instance[] num, int start, int end)
{
int mid = start + (end-start)/2;
// do what you would've done in the constructor
testValue = num[mid].getAttribute();
// no 'return null' if statement, instead, prevent the call from ever happening
// leaving 'left' / 'right' as 'null' if it doesn't
if (start <= mid-1)
left = new DTNode(num, start, mid-1);
if (mid+1 <= end)
right = new DTNode(num, mid+1, end);
// no return statement - constructors can't return anything
}
您可以像这样调用递归构造函数:
root = new DTNode(instances, 0, instances.length);
此外,从显示的代码来看,没有必要将 Instance[] a;
作为 DTNode
的成员。
关于java - Java中的决策树节点方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22872133/