Swift Algorithm Club: Swift Tree Data Structure

@wm_j_ray

I just gave the tutorial a run on b6. I got the error even before generics.

It seems like the weak semantics on the parent property is causing some trouble in the beta playgrounds. I tried instantiating the tree in a normal Xcode project and it ran fine.

For now, deleting the weak prefix for the parent property will allow you to run fine in the playgrounds. I’m going to submit a bug report to Apple regarding this.

there is error in Insertions section

func add(child: Node) {
    children.append(node)
    node.parent = self
}

should be

func add(child: Node) {
    children.append(child)
    child.parent = self
}

@ha100 - Fixed, thanks for the heads up!

don’t forget to do the parent setting part. very nice work. Thank you

Thanks for this awesome tutorial! You made algorithm easy for me! I have one confusion, “var children: [Node] = []”. This code should be “var children: [Node]? = []” , since leaf node may not have children. Please correct me if I am wrong.

A leaf node by definition has no children!
But a node could have no children, true: this is represented by the empty array. The array doesn’t also have to be optional.

We have a requirement to draw the same tree in Swift. Can you guide me how can I do it?

I did little research and figured out that we need to draw it on a Scrollview and we can use CAShapeLayer to draw the custom nodes. Am I going the correct direction?

Great tutorial. I’d like to know how to do the pattern match. For example, find all nodes match certain pattern. The return result will be a new tree with all matched nodes and their children.

Great tutorial thank you.

Just two mistakes.

First one on this sentence:
Note: If you the mapping syntax confuses you, here’s what you could have written instead:
which should be:
Note: If the mapping syntax confuses you, here’s what you could have written instead:

Second one for this code:
if !children.isEmpty {
text += " {"
for child in children {
text += child.description + ", "
}
text += "} "
}

which should be:
if !children.isEmpty {
text += " {"
for child in children {
if children.last?.value != child.value {
text += child.description + ", "
} else {
text += child.description
}
}
text += "} "
}

1

Take this for example, this is the result of I search for letter o. Any idea what algorithm I should use to filter the tree and get the result? Thanks.

You’re right on both counts. I’ve made the fix. Thanks!

The algorithm you’d want to use is either the breadth first search or depth first search. Those algorithms will allow you to reach every node in the tree. You’ll just have to check the value of the tree for the character o.

This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]