Search code examples
pythonobjectobject-reference

Recursively iterating through nodes referenced by other nodes


How could I recursively iterate through nodes with reference to a previous node? Expecting output 4,3,2,1 in the example below:

class Node:
    def __init__(self, parent, value):
        self.parent = parent
        self.value = value

    def append(self, value):
        return Node(self, value)

def list(l):
    print(l.value)
    while l.parent is not None:
        list(l.parent)

l = Node(None, 1)
l = l.append(2)
l = l.append(3)
l = l.append(4)
list(l)

Solution

  • Your class structure already succesfully passes the node's self value to its child node. The problem is your list function. while l.parent is not None: never ends, because nothing in the loop is changing the value of l. Calling list recursively will create a new context where another variable named l has a different value from the first context's l, but this has no effect on the the first l or the first loop. Recursive functions generally do not require an actual loop in order to iterate over the elements of a data structure. Try:

    def list(l):
        print(l.value)
        if l.parent is not None:
            list(l.parent)
    

    Or:

    def list(l):
        while l is not None:
            print(l.value)
            l = l.parent
    

    (I recommend the latter because the first one will crash with "maximum recursion depth exceeded" if the chain has more than 999 elements)

    Result:

    4
    3
    2
    1
    

    Bonus style tip: consider naming your function something other than list. In general you should avoid overwriting the names of built-in functions and types.