Learn

Now that we’ve built out the structure of the TreeNode, let’s add some functionality! The first step will be to add children to our TreeNode, what good is a Tree if we can’t grow branches!

We want to create two variations of the .addChild() method, one that accepts a complete TreeNode as an argument and one that accepts a String as an argument and then creates a TreeNode from that String. This technique, also called function overloading (or method overloading, depending on your programming language), is the practice of creating multiple instances of a function with different parameters and/or return types. You’ll run into this practice quite often as it serves a variety of roles, from making your code easier to use to allowing you to encapsulate (hide from the user) certain internal functions of your program.

If it only takes a dozen lines of code or so to give the user an easier way to create something, in our case just providing a String instead of creating a whole new TreeNode, it is worth the extra time spent to have a happy customer, even if that customer is you.

Note: In some use cases, trees may also include a reference to their parent node, however, in our implementation of a tree, we will not have any need for this property and omit it completely.

Instructions

1.

Inside the TreeNode class and beneath the initializer, add an empty .addChild(_:) function that accepts one parameter, a TreeNode named newChild, you’ll want to omit the argument label.

2.

Inside your new function, you need to add the newChild to the list of children. You can use the Array method .append() to do this.

3.

Define another .addChild(_:) function below the first. This one will accept one parameter, newChildData of type String, also with no argument label. Inside the function, create a new TreeNode using newChildData and append it to the children Array. Do this as one line of code.

4.

Now let’s test your code by adding some children. At the bottom of the file, after the creation of root:

  • Create a new TreeNode, branch1, with “Your tree is ” as the data.
  • Add branch1 to root using .addChild()
  • Add another child to root using the second .addChild() function, with “growing every day.” as the data.
5.

You shouldn’t have seen any errors, but how do you know if the two branches were actually added to root as children? Let’s check.

  • On the line directly after root is initialized, print out whether root’s children contains any objects using the Array’s isEmpty property.
  • Add the same print statement at the bottom of the file, after you’ve added your second child to root.

Take this course for free

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?