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))
traverse? A high-level explanation of the algorithm you're looking for is here: en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR) - kingkupps