Python 3.x 使用节点查找二叉树中的叶之和

Python 3.x 使用节点查找二叉树中的叶之和,python-3.x,binary-tree,Python 3.x,Binary Tree,我希望能够通过使用节点递归地找到二叉树中所有叶子的总和,到目前为止,我已经: class BTNode: """A node in a binary tree.""" def __init__(self: 'BTNode', item: object, left: 'BTNode' =None, right: 'BTNode' =None) -> None: """Initialize this node. """ self

我希望能够通过使用节点递归地找到二叉树中所有叶子的总和,到目前为止,我已经:

class BTNode:
  """A node in a binary tree."""

  def __init__(self: 'BTNode', item: object, 
               left: 'BTNode' =None, right: 'BTNode' =None) -> None:
    """Initialize this node.
    """
    self.item, self.left, self.right = item, left, right

  def __repr__(self):
    return 'BTNode({}, {}, {})'.format(repr(self.item), 
                    repr(self.left), repr(self.right))

  def is_leaf(self: 'BTNode') -> bool:
    return not self.left and not self.right


def tree_sum(t: BTNode) -> int:
  '''Return the sum of the leaves in t.

  >>> t = BTNode(None, BTNode(8), BTNode(9))
  >>> tree_sum(t)
  17
  '''
  sm = 0
  t1 = t.left.item
  t2 = t.right.item
  if not t.left or not t.right:
    return 0
  if t.left.is_leaf() and t.right.is_leaf():
    sm = t1 + t2 + tree_sum(t.left) + tree_sum(t.right)
  return sm

我的函数树_sum(t)不起作用,我正在努力找到一种可行的方法。我做错了什么?

您缺少一点代码

由于
t.left
t.right
将是
None
如果
t
是一片叶子,则行
t1=t.left.item
t2=t.right.item
将引发一个
AttributeError

你需要考虑到这一点:

t1 = t.left.item if t.left else None
t2 = t.right.item if t.right else None
然后

生成正确的结果(17)

也就是说,此函数不会返回所有叶子的总和(即在多级树的情况下,它不会遍历整个树)

t = BTNode(None, BTNode(8), BTNode(9))
print(tree_sum(t))