I want to recursively return the chain from the parent to the last kid of the family tree. I started with the code and don't know whats wrong with it:
class Tree:
def __init__(self,kid,parent = None):
self.kid = kid
self.parent = parent
def parent_chain(self):
if self.parent != None:
self.parent_chain()
else:
return self.kid # If no parent
a = Tree('Adam')
b = Tree('Beda')
c = Tree('Ceda')
c.parent = b
b.parent = a
print(c.parent_chain()) # Want it to return Adam --> Beda --> Ceda
There are two issues with your code:
.parent_chain()
on the parent, not the node that you're currently at. Otherwise, you will call .parent_chain()
on one node repeatedly, until you recurse past the recursion depth.Here is a code snippet that resolves these issues.
class Tree:
def __init__(self, val, kid=None, parent=None):
self.val = val
self.kid = kid
self.parent = parent
def parent_chain(self):
if self.parent:
result = self.parent.parent_chain()
result.append(self.val)
return result
else:
return [self.val]
a = Tree('Adam')
b = Tree('Beda')
c = Tree('Ceda')
c.parent = b
b.parent = a
print(c.parent_chain()) # Prints ['Adam', 'Beda', 'Ceda']