Skip to Content
Trees: Python
Tree Implementation IV: Traversing

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"



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


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.

Folder Icon

Sign up to start coding

Already have an account?