我是编程新手,正在尝试在 Python 中计算二叉树的深度。我相信我的错误是因为深度是 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