1

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 to find the biggest number through all the possible paths. Here is an example

       8
   3      11
10   2  32  6

returns 8+11+32=51

I feel that this is a recursion problem but I am stuck with my code and keep getting errors. I think that I am approaching this incorrectly. Below is my code:

# 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
1
  • can you include the full code ? including the structure of each node and also sum_to_deepest function Commented Sep 20, 2014 at 21:50

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.