2017-08-07 54 views
1

這是我在Python中創建一切BST代碼工作正常,但是當我訪問高度功能,它提供了錯誤,如「AttributeError的:‘NoneType’對象有沒有屬性高度「我是新來的Python中的數據結構的任何幫助將appriciatedAttributeError的:「NoneType」對象在BST蟒蛇高度沒有屬性高度

class Node: 
     def __init__(self, data): 
      self.left = None 
      self.right = None 
      self.data = data 
     def insert(self, data): 
      if self.data: 
       if data < self.data: 
        if self.left is None: 
         self.left = Node(data) 
        else: 
         self.left.insert(data) 
       elif data > self.data: 
        if self.right is None: 
         self.right = Node(data) 
        else: 
         self.right.insert(data) 
      else: 
       self.data = data 

     def print_tree(self): 

      if self.left: 
       self.left.print_tree() 
      print (self.data) 
      if self.right: 
       self.right.print_tree() 

     def height(self): 
      if self.data is None: 
       return 0 
      else: 
       return 1 + max(self.left.height(),self.right.height()) 

    root = Node(8) 
    root.insert(3) 
    root.insert(10) 
    root.insert(1) 
    root.insert(6) 
    root.insert(4) 
    root.insert(7) 
    root.insert(14) 
    root.insert(13) 
    root.print_tree() 
    root.height() 
+0

對於葉節點,'self.data'不是無,但'self.left'和'self.right'是無,因此這個問題。 –

回答

1

葉節點在你的樹,self.data將被設置爲葉節點的值,但self.leftself.rightNone。但即使在此之前,可以有節點,其中左或右的孩子是None因爲我們嘗試節點,並得到其高度,我們得到NoneTypeAttributeError

在用於height代碼 -

def height(self): 
    if self.data is None: 
     return 0 
    else: 
     return 1 + max(self.left.height(),self.right.height()) 

當遞歸到達節點,其中任leftright節點是無,上面的代碼會失敗,因爲它會嘗試訪問self.left.height()self.right.height(),和一個他們是無。

我們可以添加一個簡單的檢查,看看是否self.leftself.rightNone,並基於它得到它的高度。

+0

謝謝Machane! –

0

如果你遇到一個錯誤,它意味着你嘗試使用None的領域。因爲你的樹是有限的,你有一個沒有任何數據的葉子。我看你有沒有在self.data字段被分配到一個值,但self.leftself.right沒有代碼的地方。同時,您在height方法中獲得的字段值,您只能檢查self.data。這對我來說沒有意義。

另外,我建議嘗試pdb或其他調試工具。

相關問題