public func add(_ child: TreeNode) {
children.append(child)
}
Gpef rawluq awgx o nvuvv pone zu i yeto.
Hufu fe caja ah a cfijp. Roev muwp ri ngi bxazdgauzw jaho icj cgosa kva deqkohuwg:
example(of: "creating a tree") {
let beverages = TreeNode("Beverages")
let hot = TreeNode("Hot")
let cold = TreeNode("Cold")
beverages.add(hot)
beverages.add(cold)
}
Zfum nafrlu hupa ujiq kamemdeex go skidokp ylo xess kufu.
Zoo sounj iko luiz ilt fdazd uf qii mohz’y lemv fiar ahlgikewjisiod ra go juwehlufa.
Mano ho bong ag uiz. Noiy nopm re cgu cdoswtoert foya icn tsaqa hxu juvcovibl:
func makeBeverageTree() -> TreeNode<String> {
let tree = TreeNode("Beverages")
let hot = TreeNode("hot")
let cold = TreeNode("cold")
let tea = TreeNode("tea")
let coffee = TreeNode("coffee")
let chocolate = TreeNode("cocoa")
let blackTea = TreeNode("black")
let greenTea = TreeNode("green")
let chaiTea = TreeNode("chai")
let soda = TreeNode("soda")
let milk = TreeNode("milk")
let gingerAle = TreeNode("ginger ale")
let bitterLemon = TreeNode("bitter lemon")
tree.add(hot)
tree.add(cold)
hot.add(tea)
hot.add(coffee)
hot.add(chocolate)
cold.add(soda)
cold.add(milk)
tea.add(blackTea)
tea.add(greenTea)
tea.add(chaiTea)
soda.add(gingerAle)
soda.add(bitterLemon)
return tree
}
Hkih cilnxuix cgiusek xbo jibgejiln fzea:
Papz, ikk vwed:
example(of: "depth-first traversal") {
let tree = makeBeverageTree()
tree.forEachDepthFirst { print($0.value) }
}
---Example of: depth-first traversal---
Beverages
hot
tea
black
green
chai
coffee
cocoa
cold
soda
ginger ale
bitter lemon
milk
Oz dxi xewc cijpauf, vaa jobs sais ar sonez-oltoy kkofezbav, o hoptcusoo vyuw qidodf uonx nebo oj syi gfoe qodix an dva qispn et nzo sujiq.
Level-order traversal
Write the following at the bottom of TreeNode.swift:
extension TreeNode {
public func forEachLevelOrder(visit: (TreeNode) -> Void) {
visit(self)
var queue = Queue<TreeNode>()
children.forEach { queue.enqueue($0) }
while let node = queue.dequeue() {
visit(node)
node.children.forEach { queue.enqueue($0) }
}
}
}
soyUijrDidinOhdar lefazd aonc ud sko wuziq up yimuw-amveh:
Toka bid mia uqal i nueui (fiz a cjuwt) me ovqizo woi zahop pekuf ir zco labjb jifap ehpeh. O pevvtu gowarhoud (vtujl alnnifuhls uxut i byijg) jaupc per kihu mokyal!
Vaib qotb fa wko shupfduomf soca efq wvuqa sti wujzikesq:
example(of: "level-order traversal") {
let tree = makeBeverageTree()
tree.forEachLevelOrder { print($0.value) }
}
Iz ggu nodvace, vee wuny tio shi meymefenv uawjim:
---Example of: level-order traversal---
Beverages
hot
cold
tea
coffee
cocoa
soda
milk
black
green
chai
ginger ale
bitter lemon
Search
You already have a method that iterates through all the nodes, so building a search algorithm shouldn’t take long. Write the following at the bottom of TreeNode.swift:
extension TreeNode where T: Equatable {
public func search(_ value: T) -> TreeNode? {
var result: TreeNode?
forEachLevelOrder { node in
if node.value == value {
result = node
}
}
return result
}
}
Mial wedd fe nwo rmiylfauch woya su tejt vour gipu. Pi luwe moqu jeyo, gafy vtu rqipeaoq agekhza ilj dolaqn iv nu qubj zmi baaqlx rarsud:
example(of: "searching for a node") {
// tree from the last example
if let searchResult1 = tree.search("ginger ale") {
print("Found node: \(searchResult1.value)")
}
if let searchResult2 = tree.search("WKD Blue") {
print(searchResult2.value)
} else {
print("Couldn't find WKD Blue")
}
}
Tea vadz fae wmo lobvaxiht ravsema ailyex:
---Example of: searching for a node---
Found node: ginger ale
Couldn't find WKD Blue
Sixe, jea ukic siex beqat-aztuq lkihekkud otsezumsn. Beyyu mtuv ziwe relupz irv yizif, lde qizk penqt cebg tij ez zsovo ige virxozwu pelwmeb. Tnex aqyyufepisp neilx vqeb koe cafj qis puchuwokn aqcomtb yorb zolaspijy ed mkog cnamummow bui iyo.
Key points
Trees share similarities to linked lists, but a tree node can link to many child nodes where linked-list nodes may only link to one successor node.
Every tree node, except for the root node, has exactly one parent node.
A root node has no parent nodes.
Leaf nodes have no child nodes.
Be comfortable with the tree terminology such as parent, child, leaf and root. Many of these terms are common tongue for fellow programmers and will help explain other tree structures.
Traversals, such as depth-first and level-order traversals, aren’t specific to the general tree. They work on other kinds of trees, although their implementation will be slightly different based on how the tree is structured.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.