Python 树中的递归

Python 树中的递归,python,recursion,tree,decision-tree,Python,Recursion,Tree,Decision Tree,我正在用Python构建一个简单的二叉决策树。我使用递归来构建树,但是,作为一个对这个概念没有把握的人,我遇到了一些麻烦。我想在树到达某个深度时停止递归,但我不确定在哪里增加值,因此它一次构建多个分支。现在,树只是向右分支,直到到达5,然后停止。在何处/如何增加该值?现在,我在函数底部的for循环中执行它 def buildTree(currentNode, maxDepth, currentDepth, minGain, currentGain, allFeatures): print(cur

我正在用Python构建一个简单的二叉决策树。我使用递归来构建树,但是,作为一个对这个概念没有把握的人,我遇到了一些麻烦。我想在树到达某个深度时停止递归,但我不确定在哪里增加值,因此它一次构建多个分支。现在,树只是向右分支,直到到达5,然后停止。在何处/如何增加该值?现在,我在函数底部的for循环中执行它

def buildTree(currentNode, maxDepth, currentDepth, minGain, currentGain, allFeatures):
print(currentNode.data)
if maxDepth <= currentDepth:
    return None
else:
    splitOn, hasFeat, noFeat, allFeatures, maxGain = split(currentNode, allFeatures)
    print(len(hasFeat), len(noFeat))
    currentNode.left = Tree()
    currentNode.left.vectors = hasFeat
    currentNode.left.data = splitOn
    currentNode.left.entropy = getEntropy(getInstances(currentNode.left.vectors))
    currentNode.right = Tree()
    currentNode.right.vectors = noFeat
    currentNode.right.data = "!" + splitOn
    currentNode.right.entropy = getEntropy(getInstances(currentNode.right.vectors))
    nodeList = [currentNode.right, currentNode.left]
    for node in nodeList:
        return buildTree(node, maxDepth, currentDepth + 1, minGain, maxGain, allFeatures)
def构建树(currentNode、maxDepth、currentDepth、minGain、currentGain、allFeatures):
打印(currentNode.data)

如果maxDepth您的函数只能返回一次,这就是为什么它只构建正确的节点;它也不应该返回其子节点。您是否尝试过将最后几行替换为:

for node in nodeList:
    node = buildTree(node, maxDepth, currentDepth + 1, minGain, maxGain, allFeatures)
return currentNode

递归调用应该在
currentNode.left
currentNode.right
上使用

代码应该类似于:

def buildTree(currentNode, maxDepth, currentDepth, minGain, currentGain, allFeatures):
    print(currentNode.data)
    if maxDepth <= currentDepth:
        return None
    else:
        splitOn, hasFeat, noFeat, allFeatures, maxGain = split(currentNode, allFeatures)
        print(len(hasFeat), len(noFeat))
        currentNode.left = buildTree(Tree(), maxDepth, currentDepth + 1, minGain, maxGain, allFeatures)
        currentNode.left.vectors = hasFeat
        currentNode.left.data = splitOn
        currentNode.left.entropy = getEntropy(getInstances(currentNode.left.vectors))
        currentNode.right = buildTree(Tree(), maxDepth, currentDepth + 1, minGain, maxGain, allFeatures)
        currentNode.right.vectors = noFeat
        currentNode.right.data = "!" + splitOn
        currentNode.right.entropy = getEntropy(getInstances(currentNode.right.vectors))
        nodeList = [currentNode.right, currentNode.left]
        return nodeList
def构建树(currentNode、maxDepth、currentDepth、minGain、currentGain、allFeatures):
打印(currentNode.data)

如果maxDepth,我可以看到它是如何工作的,但是节点需要属性“vectors”来决定拆分树的功能,如果我在该点递归,它就没有这个功能。因此,首先设置属性,然后进行递归调用(切换行的顺序)。