Find the maximum sum of a tree in python

前端 未结 1 1567
一生所求
一生所求 2021-01-24 13:38

I have a tree of numbers that I want to be able to find the sum of numbers. Below each number are two children to the left and right Of all the possible paths, I want to be able

相关标签:
1条回答
  • 2021-01-24 14:05

    Without knowing the data structure you are using is difficult to give you an answer. But I think you are looking for somenthing like this:

    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
    
    0 讨论(0)
提交回复
热议问题