简体   繁体   中英

recursion of objects and methods in python

I wanna create a class which consist of parents and children and a recursion method to call the last child :

class MyClass:
    def __init__(self,val,child =None):
        self.val = val
        self.child = child
    def findLastChildVal(self):
        if self.child ==None:
            return self.val
        return (...)

c = MyClass("I'm child")
p = MyClass("I'm parent",c)
p.findLastChildVal()

I have no Idea what to write instead of (...). It's confusing.

This is a classic recursion problem, in my opinion it will be much easier to use a static function instead of a member function:

class MyClass:
    def __init__(self, val, child =None):
        self.val = val
        self.child = child

    @staticmethod
    def find_last_child_val(current_node: MyClass):
        if current_node.child == None:
            return current_node.val
        else:
            return MyClass.find_last_child_val(current_node.child)

c = MyClass("I'm child")
p = MyClass("I'm parent", c)
MyClass.find_last_child_val(p)

Update:

Pay attention that searching for a child using a recursion like this, is not efficient. find_last_child_val() runs in O(n) complexity. It is much more efficient to perform n iterations in a for loop instead of a recursion. If you can't think of a way to reduce the tree traversal complexity, I suggest using a different data structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM