0
votes

A tree (such as an inheritance tree) is a data structure with parent nodes and child nodes. For example

               A
              /  |
             B     C
            / |     |
           D   E     F

We will represent the tree a a dictionary with node name as key, and list of child names values.

{"A":["B", "C"], "B":["D","E"], "C":["F"], "D":[], "E":[], "F":[]}

Consider each ordered list and use recursion to traverse the list 'depth first`.

Return a string of letters in order of visiting during depth first traversal. For this example, the system should return "ABDECF"

:param parent: current node being processed
:param tree: dictionary of the entire tree - do not modify this in recursive call
:return: String representing depth first traversal

I understand inheritance pretty well, I just don't understand what exactly I am supposed to do with it in this case. Any help would be appreciated.

class Program4:
    def __init__(self):
        self.counter=0

    def traverse(self, parent, tree):
        self.counter += 1 # Leave this counter alone

        #@todo - fix this.
        #   call recursion with self since instance method
        #  This is doable in no more than six lines of code

        pass

if __name__ == "__main__":
    tree = {"A":["B", "C"], "B":["D","E"], "C":["F"], "D":[], "E":[], "F":[]}

    print("Tree:",tree)
    p=Program4()
    print("Depth first:",p.traverse("A",tree))
1
Have you attempted any implementation of traverse? A high-level explanation of the algorithm you're looking for is here: en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR) - kingkupps

1 Answers

1
votes

Something like the following will do:

class Program4:
    # ...
    def traverse(self, parent, tree):
        # ...
        s = parent
        for child in tree.get(parent, []):
            s += self.traverse(child, tree)
        return s

The base case case is a leaf node without children in which case (as you can verify) the parent itself is returned. In all other cases the traversals of the parent's subtrees are appended to it.

You could do that in a one-liner, using str.join and a generator:

# ...
def traverse(self, parent, tree):
    return parent + ''.join(self.traverse(c, tree) for c in tree.get(parent, []))

>>> p = Program4()
>>> print("Depth first:", p.traverse("A", tree))
Depth first: ABDECF