I am trying to define a recursive method to walk all the nodes of a tree. I defined the Tree as the following:
class Tree(object):
def __init__(self, value, lson=None, sibling=None):
self.value = value
if lson:
self.lson = Tree(lson)
else:
self.lson = None
if sibling:
self.sibling = Tree(sibling)
else:
self.sibling = None
def __str__(self):
return str(self.value)
I have the following function that works:
def walk_tree(t):
# walk in order
print t
if t.lson:
walk_tree(t.lson)
if t.sibling:
walk_tree(t.sibling)
return t
How do I turn this to an instance method?
def walk_tree(self):
# walk in order
print self.value
if self.lson:
self.walk_tree(self.lson)
if self.sibling:
self.walk_tree(self.sibling)
return self
This will result in Max recursion depth error...
a. Is this how do you implement a recursive method?
b. Is there a justification here to use yield
?
c. Is there a justification here to use @staticmethod
which recieves a Tree
instance?