If you look back, all of our work has been exclusively in the TreeNode
class, in fact, we haven’t even defined a Tree
Class yet, but this is where we will create our actual .print()
methods.
There are two functions we will create, a generic .print()
method that we will use to print the whole tree and a .printFrom(_:_:)
method that will allow us to provide a specific entry point into our tree and print from there. The .print()
method will simply call the .printFrom(_:_:)
method using the root as the entry point.
Similar to the .removeChild(_:)
method, the .printFrom(_:_:)
method will use recursion to iterate through all the elements of the tree.
If you look at the Tree.swift file, you will see that we’ve added the Tree
class to the bottom of the file. It is a simple structure that has only one property, the root
of the tree. We’ve also reduced the information in the TreeNode
’s description
variable so our printing is easier to read. We’ve also made some changes to our CustomStringConvertible
extension and other minor updates.
Instructions
Inside the Tree
class and beneath the initializer, create an empty function, printFrom
that has two parameters:
currentNode
of typeTreeNode
depth
of typeInt
with a default value of 0
The function does not have a return value and both parameters should omit argument labels.
Inside the function create a constant, depthMarker
and initialize it to a String that repeats (String Documentation) the sequence “–|” depth
amount of times. This will be used to indicate what level of the tree you are printing.
On the next line, print the depthMarker
and currentNode
using String Interpolation. Since we will be defining our own .print()
method next, when you call .print()
here, you will have to use the package name as well. In this case, the basic .print()
method is in the Swift
package so the call will be in the format: Swift.print(\(variable))
.
Now that you’ve displayed the current depth and current node data, the next step is to begin the recursive algorithm. Create an empty for-in
loop that iterates over each child
in currentNode.children
after the last print statement.
Inside the loop, call the printFrom(_:_:)
method with child
and depth + 1
as arguments. Uncomment the line of code that calls .printFrom(child4)
on the poeFamilyTree
near the bottom of the file and see your hard work!
The normal case for printing a tree begins at the root. Following best practices, you need to create a generic .print()
method that does just that, without asking the user to provide an entry point. Underneath the .printFrom(_:_:)
method, add a new .print()
method that has no parameters. Its only line of code should be to call .printFrom(_:_:)
on the root
, you will leave the depth argument absent because you want to use its default value of 0
. Uncomment the last two lines of code in the file and see how it looks.
Try building your own tree and printing it from the root and a different entry point to see how the statements differ.