TransWikia.com

Run Tree Structure in Python

Stack Overflow Asked by Tianhe Xie on November 30, 2020

I implemented tree structure as follow:

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()

I’m not sure how to run it, it’s giving me an error on Solution.isBST(self, two), I guess it’s because self is not defined.

However, if I do :

Solution.isBST(two)

It says the function is missing an argument. So I guess self must be called?.
If I do

self.isBST(two)

Then, I’m not sure where to reference self in the first place. Anyone knows how to run it?

One Answer

So, you need either to instantiate an object of class Solution solution = Solution() and then call it's methods: solution.isBST(two), or you need to define isBST as a class method by removing self from its definition: def isBST(curr):. Then it is not needed to instantiate an object, and you can call class method directly: Solution.isBST(two). The decision is based on your vision of program architecture.

Answered by Enrico on November 30, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP