在python中查找树的最大和

在python中查找树的最大和,python,tree,Python,Tree,我有一个数字树,我希望能够找到数字的总和。在每个数字下面是所有可能路径的左边和右边的两个子项,我希望能够通过所有可能路径找到最大的数字。这里有一个例子 8 3 11 10 2 32 6 返回8+11+32=51 我觉得这是一个递归问题,但我一直在使用我的代码,并且不断出现错误。我认为我的做法是错误的。下面是我的代码: # Returns root key value def getRootValue(root): return root # Re

我有一个数字树,我希望能够找到数字的总和。在每个数字下面是所有可能路径的左边和右边的两个子项,我希望能够通过所有可能路径找到最大的数字。这里有一个例子

       8
   3      11
10   2  32  6
返回8+11+32=51

我觉得这是一个递归问题,但我一直在使用我的代码,并且不断出现错误。我认为我的做法是错误的。下面是我的代码:

# Returns root key value
def getRootValue(root):
    return root

# Returns reference to left child
def getLeftChild(root):
    value=None
    if root.leftChild!=None:
        value=root.leftChild
    return value

# Returns reference to right child
def getRightChild(root):
    value=None
    if root.rightChild!=None:
        value = root.rightChild
    return value

def sum_of_branch(root):
    sum=0  
if root.getLeftChild() ==None and root.getRightChild()==None:
    return rounds
else:
    rounds+=rounds+1
    keys_sum[depth]=sum+root.key
    return sum_to_deepest(root.left), sum_to_deepest(root.right)
    if root.getLeftChild()!=None:
        rounds+=root.getLeftChild().branchLenSum()
    if root.getRightChild()!=None:
        rounds+=root.getRightChild().branchLenSum()
    return rounds

如果不知道您使用的数据结构,就很难给出答案。但我认为你在寻找这样的东西:


你能包括完整的代码吗?包括每个节点的结构以及求和函数
def sum_of_branch(root):
    # If it has not childs we have arrived at the end of the tree.
    # We return the value of this child.
    if root.getLeftChild() ==None and root.getRightChild()==None:
        return getRootValue(root)
    else:
        # If it has children we calculate the sum of each branch. 
        leftSum = sum_of_branch(root.getLeftChild())
        rightSum = sum_of_branch(root.getRightChild())
        # And return the maximun of them.
        if leftSum > rightSum:
            return getRootValue(root) + leftSum
        else:
            return getRootValue(root) + rightSum