Learn

Our implementation has covered adding and removing nodes. Let’s expand the functionality and add the ability to move through connected nodes.

Tree traversal is a standard operation for finding nodes with a specific value or printing all the nodes available in a tree.

We’d like to do the following:

root = TreeNode('Founder') child_a = TreeNode('VP of Bananas') child_b = TreeNode('Executive Assistant') root.add_child(child_a) root.add_child(child_b) root.traverse() # prints "Founder", "VP of Bananas", "Executive Assistant"

Instructions

1.

Define a traverse method inside of the TreeNode class, it will only take self as an argument. Within .traverse(), print the node’s value.

2.

After printing self.value, loop through self.children and print their values. Call .traverse() on root. You should see the value of each node printed to the screen.

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?