pythonclassrecursionnodeschain

Recursively finding elements of the chain


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

Solution

  • There are two issues with your code:

    1. Whenever you're assembling the chain, you need to call .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.
    2. You're setting strings to be the values of the kid references. You probably want to store some sort of separate label. This doesn't directly affect what you're trying to do here, but it's almost certainly a mistake, and it will have an effect if you want to use the child pointers in any way (e.g. if you wanted to extend this code to read from parent to child).

    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']