Type error: unpacking tuples Recursive function call

Type error: unpacking tuples Recursive function call

我有如下一段代码:

def myCalculation(self, root, max_val): 
        
        if root == None:
            return -1
        
        LH = 1 + (self.myCalculation(root.left, max_val))[0]
        RH = 1 + (self.myCalculation(root.right, max_val))[0]
        
        ret = LH+RH
        
        if max_val < ret:
            max_val = ret
            
        return (max(LH, RH), max_val)

在这里,我 return 两个值,因为对于堆栈上的最后一个函数调用退出函数必须 return max_val 到调用函数。因此,当我在函数的第 3 行和第 4 行执行函数调用并尝试使用 return 值时,它给出了下面描述的 TypeError。

错误是:

> TypeError: 'int' object has no attribute '__getitem__'

完整追溯:

TypeError: 'int' object has no attribute '__getitem__'
    LH = 1 + (self.myCalculation(root.left, max_val))[0]
Line 14 in myCalculation (Solution.py)
    LH = 1 + (self.myCalculation(root.left, max_val))[0]
Line 14 in myCalculation (Solution.py)
    LH, max_val1 = 1 + self.myCalculation(root.left, 0)
Line 32 in diameterOfBinaryTree (Solution.py)
    ret = Solution().diameterOfBinaryTree(param_1)
Line 67 in _driver (Solution.py)
_driver()

(Solution.py)中的第 77 行

我不太明白在递归中打包和解包元组的问题是什么?

问题是您的基本情况 return 是一个 单一 值。但是,您可以通过删除 return 多个值和额外参数 max_val 的需要来简化您的算法。我们可以计算一棵树的diametert-

def diameter(t):
  if not t:
    return 0
  else:
    return max(                            # return maximum of:
      diameter(t.left),                    # diameter of left
      diameter(t.right),                   # diameter of right
      1 + height(t.left) + height(t.right) # or diameter of t itself
    )

其中树 theight 定义为 -

def height(t):
  if not t:
    return 0
  else:
    return 1 + max(height(t.left), height(t.right))

你可以在Solution中写myCalculation class -

class Solution:
  def myCalculation(self, root):
    return diameter(root)

因为height会在子节点上被多次调用,所以这个程序可以使用lru_cache进行优化,有效地“记忆”函数-

from functools import lru_cache

@lru_cache
def height(t):
  # ...