2014-09-20 29 views
0

我有一棵數字樹,我希望能夠找到數字的總和。在每個數字的下方有兩個左右兒童在所有可能的路徑中,我希望能夠通過所有可能的路徑找到最大的數字。下面是一個例子在python中找到一棵樹的最大數量

 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 
+0

可以包括完整的代碼?包括每個節點的結構以及sum_to_deepest函數 – g4ur4v 2014-09-20 21:50:05

回答

1

不知道你使用的數據結構很難給你一個答案。但我認爲你正在尋找somenthing這樣的:

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 
相關問題