簡體   English   中英

在 Python 中計算二叉樹的深度

[英]calculating depth of a binary tree in Python

我是編程新手,正在嘗試用 Python 計算二叉樹的深度。 我相信我的錯誤是因為 depth 是 Node 類的方法而不是常規函數。 我正在嘗試學習 OOP 並希望使用一種方法。 這可能是一個新手錯誤......這是我的代碼:

class Node:

    def __init__(self, item, left=None, right=None):
        """(Node, object, Node, Node) -> NoneType
        Initialize this node to store item and have children left and right.
        """
        self.item = item
        self.left = left
        self.right = right

    def depth(self):
        if self.left == None and self.right == None:
            return 1

        return max(depth(self.left), depth(self.right)) + 1

i receive this error:

>>>b = Node(100)

>>>b.depth()

1 

>>>a = Node(1, Node(2), Node(3))

>>>a.depth()

Traceback (most recent call last):
  File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in depth
builtins.NameError: global name 'depth' is not defined
def depth(self):
    if self.left == None and self.right == None:
        return 1

    return max(depth(self.left), depth(self.right)) + 1

應該

def depth(self):
    return max(self.left.depth() if self.left else 0, self.right.depth() if self.right else 0) + 1

一個更易讀的版本:

def depth(self):
    left_depth = self.left.depth() if self.left else 0
    right_depth = self.right.depth() if self.right else 0
    return max(left_depth, right_depth) + 1

問題是沒有函數depth 它是Node對象的一個​​方法,因此您需要從對象本身(左右)調用它。 我將代碼縮短為self.left.depth() if self.left else 0self.right.depth() if self.right else 0以刪除您以前擁有的檢查(它們現在是隱式的),因為我相信完全有可能左邊是None而右邊是Node ,反之亦然,這將導致原始代碼拋出AttributeError因為None沒有方法depth

編輯

回答關於<something> if <some condition> else <otherwise>塊的問題:

如果<some condition>為真-y(視為真),則該行給出<something> ,如果<some condition>為假-y(視為假),則給出<otherwise>

為了清楚起見,我建議您這樣編寫depth方法:

def depth(self):
    current_depth = 0

    if self.left:
        current_depth = max(current_depth, self.left.depth())

    if self.right:
        current_depth = max(current_depth, self.right.depth())

    return current_depth + 1

錯誤來自這一行:

return max(depth(self.left), depth(self.right)) + 1

您將深度用作函數並嘗試將其應用於左右節點。 因為左右節點也是節點,所以有depth方法。

您應該像這樣調用 depth 方法:

return max(self.left.depth(), self.right.depth()) + 1

self 參數被隱式傳遞給 depth 方法,但是將它與點運算符一起使用會告訴 Python 此方法屬於一個 Node 實例,而不是其他未綁定到對象的函數。

您需要考慮四種情況:

  1. 兩個子樹都是空的。
  2. 只有左子樹是空的。
  3. 只有右子樹是空的。
  4. 兩個子樹都不是空的。

您已經涵蓋了案例 1 和案例 4,但錯過了案例 2 和 3。修復方法:

# Return height of tree rooted at this node.
def depth(self):
    if self.left == None and self.right == None:
        return 1
    elif self.left == None:
        return self.right.depth() + 1
    elif self.right == None:
        return self.left.depth() + 1
    else:
        return max(self.left.depth(), self.right.depth()) + 1

暫無
暫無

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

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