With our private add(_:to:) function complete, it is time to implement our public-facing add(_:) method. Users don’t need to be able to add a value to specific subtrees in our structure, actually, if we allowed them to do this, it might break the rules of our BST.

The public-facing function will also handle the case of adding the first value to our tree, the root. We don’t have an initializer for the BinarySearchTree class because the instance variable is optional. This is common when you want a user to be able to create an instance of your class without having to know any of the values they want to add yet.

Our public function will also simply allow the user to add any value that is the same type of the tree using generics to enforce the type conformance.



Underneath the comment for the add function in the “Public Functions” section, create a new empty function, add(_:), that takes one parameter, value of type T, it should not have an argument label.


Inside the function, create a new constant, node, equal to a new BinaryNode with value.


Under your new node, create an if-let statement that creates root if self.root exists. Inside the if clause, call the private add(_:to:) function passing node, to the new root constant.


Add an else clause to the if-let statement, it will handle the case when there is no root already in the BinarySearchTree. Inside the else clause, set self.root equal to node.


Under the instantiation of numberTree at the bottom of the file, add the Integers 5, 6, and 2 to the tree by calling add(_:) three times.

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?