Python中的运行树结构
我实现了如下树结构:Python中的运行树结构,python,Python,我实现了如下树结构: class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxDepth(self, root): ... def isBST(self, curr): ... def main
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxDepth(self, root):
...
def isBST(self, curr):
...
def main():
one = TreeNode(1)
two = TreeNode(2)
three = TreeNode(3)
two.left = one
two.right = three
Solution.isBST(self, two)
if __name__ == "__main__":
main()
我不知道如何运行它,它给了我一个关于解决方案的错误。isBST(self,two)
,我想这是因为self没有定义
但是,如果我这样做:
Solution.isBST(two)
它表示函数缺少一个参数。所以我想一定叫赛尔夫吧?。
如果我这样做
那么,我不确定首先在哪里引用self。有人知道如何运行它吗?因此,您需要实例化Solution类的对象
Solution=Solution()
,然后调用它的方法:Solution.isBST(两个)
,或者您需要通过从其定义中删除self
,将isBST
定义为类方法:def isBST(curr):
。然后不需要实例化对象,您可以直接调用class方法:Solution.isBST(two)
。这个决定是基于您对程序架构的看法。在main
中,什么是self
?您在这里调用它时没有任何参数:main()
@ForceBru嗨,我刚刚更新了我的问题。我需要运行和测试我的方法,但我不知道如何去做。我只是在尝试将self
放在main
中是否有效。您的思路是正确的:isBST
是类解决方案的一个方法,因此类应该参与调用该方法。请看一些OOP教程,例如:
self.isBST(two)