Learn

We have a working TreeNode class, but there’s no time to enjoy a refreshing glass of lemonade. Trees are all about data hierarchy, and we need a parent-child relationship to make that work.

To review: child nodes are held as references by another instance of TreeNode, known as the parent node.

parent = TreeNode('CEO') child = TreeNode('Executive Assistant') print(parent.children) # [] parent.add_child(child) print(parent.children) # [child]

We’ll store the references to child nodes in a Python list and define an add_child method on our TreeNode class which will add nodes to that list.

Instructions

1.

Modify our __init__() method by setting self.children to be an empty list.

2.

Define add_child on the TreeNode class. It should take self and child_node as parameters. In the body of add_child, start with print("Adding " + child_node.value).

3.

After the print statement, use a list method to add the child_node to self.children.

4.

Finally, call add_child on root and pass child as an argument.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?