簡體   English   中英

計算二叉樹中的路徑

[英]Calculate paths in binary tree

嗨,在這段代碼中,我試圖計算二進制樹(數據結構)中的路徑。 但是在某些情況下,它會給我一個錯誤,說“ AttributeError:'int'對象沒有屬性'left'”。如何解決此問題? 例如在這種情況下

tree = BTNode(None, BTNode(None,1, 5), BTNode(8))

我將遇到屬性錯誤。

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(self.item, str(self.left), 
             str(self.right))


 def tree_paths(t: BTNode) -> int:
  '''Return number of paths to get from root of t,
  to all houses, and back to t.

  >>> tree_paths(BTNode(None, BTNode(4), BTNode(5)))
  4
  '''
  ll = 0
  rl = 0
  if t is None:
     return -2
  if t.left is not None and t.left != int:
     ll = tree_paths(t.left) + 2
  if t.right is not None and t.right != int:
     rl = tree_paths(t.right) + 2

  return ll + rl

我看到的錯誤是:

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    tree_paths(t)
  File "C:\Users\ma\Desktop\CSC148\lab7\trick.py", line 60, in tree_paths
    ll = tree_paths(t.left) + 2
  File "C:\Users\ma\Desktop\CSC148\lab7\trick.py", line 60, in tree_paths
    ll = tree_paths(t.left) + 2
  File "C:\Users\ma\Desktop\CSC148\lab7\trick.py", line 59, in tree_paths
    if t.left is not None and t.left != int:
AttributeError: 'int' object has no attribute 'left'

該異常可以准確告訴您出了什么問題。 節點的left是整數,而不是BTNode (根據您的類型注釋,它應該是leftright )。

這里的問題是BTNode(None, 1, 5) 這將創建一個BTNode ,其item = Noneleft = 1right = 5 leftright的需要是BTNodes 所以代替:

tree = BTNode(None, BTNode(None, 1, 5), BTNode(8))

嘗試:

tree = BTNode(None, BTNode(None, BTNode(1), BTNode(5)), BTNode(8))

有關將來如何防止這種情況的一些想法:

請注意,類型注釋在Python中是可選的,並且不由解釋器強制執行。 如果要檢查程序是否鍵入正確,則需要在代碼庫上運行mypy 它將出於以下幾個原因而抱怨:

  1. BTNode(None, 1, 5) -因為15不是BTNode
  2. 該類型的leftright的需要是Optional[BTNode]因為它們可以Nonefrom typing import Optional

如果您使用命名的args構造樹,則可能更容易看到這一點:

tree = BTNode(item=None, left=BTNode(item=None, left=1, right=5), right=BTNode(8))

還要研究type.Generic,以便在從BTNode取出item時可以更多地利用類型系統(而不必進行不安全的強制轉換)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM