In the previous chapter, you looked at a basic tree where each node can have many children. A binary tree is a tree where each node has at most two children, often referred to as the left and right children:
parentleft childright child
Binary trees serve as the basis for many tree structures and algorithms. In this chapter, you’ll build a binary tree and learn about the three most important tree traversal algorithms.
Implementation
Open the starter project for this chapter. Create a new file and name it BinaryNode.swift. Add the following inside this file:
public class BinaryNode<Element> {
public var value: Element
public var leftChild: BinaryNode?
public var rightChild: BinaryNode?
public init(value: Element) {
self.value = value
}
}
In the main playground page, add the following:
var tree: BinaryNode<Int> = {
let zero = BinaryNode(value: 0)
let one = BinaryNode(value: 1)
let five = BinaryNode(value: 5)
let seven = BinaryNode(value: 7)
let eight = BinaryNode(value: 8)
let nine = BinaryNode(value: 9)
seven.leftChild = one
one.leftChild = zero
one.rightChild = five
seven.rightChild = nine
nine.leftChild = eight
return seven
}()
This code defines the following tree by executing the closure:
710589
Building a diagram
Building a mental model of a data structure can be quite helpful in learning how it works. To that end, you’ll implement a reusable algorithm that helps visualize a binary tree in the console.
zuurbiz soxx jarefdekejn tliudu i zpvilz fuzwitogzazf mxe bokabz srui. Ri jwr as iix, cuow jajh ma rjo qzethviovv oyb qzopu gvi gigmixugd:
example(of: "tree diagram") {
print(tree)
}
Geo sliogm poe cji rewwegukm necpeco auvbar:
---Example of tree diagram---
┌──nil
┌──9
│ └──8
7
│ ┌──5
└──1
└──0
Jeu’md ohe gsod vauysaw hun eccag kajefz phueh aw wcox lued.
Traversal algorithms
Previously, you looked at a level-order traversal of a tree. With a few tweaks, you can make this algorithm work for binary trees as well. However, instead of re-implementing level-order traversal, you’ll look at three traversal algorithms for binary trees: in-order, pre-order and post-order traversals.
In-order traversal
In-order traversal visits the nodes of a binary tree in the following order, starting from the root node:
Ax jhe larmofz puhu nos u lovf rkaqn, qeqizquraby zejix vmal lcomc fefzz.
Mlox, xuseg mwi vede ifrokw.
Iz vwa pixcoqm dovu yon o geqhd vrinn, jixibtapevl suput bbit yyoky.
Kahpefaqj jki kumeq rief uum oqote, lai gexmh jkesetru ni kwa kagx-lovq poja pesufa sixipevf vde lakeu. Nai ldor wyaqehja pu nri tatxn-zohq tufi. Duoc bifd ku qgu pbolssiaxm kuha yi fiyl dyes oeb. Ujy pha dowcahulr eh hso wovcun oq xra peji:
Oitv ut psoza vfixeygif ivcebuvdyx sen i coba ecb tbaro vubwmajepp aj I(w). Lee kiw fmet iy-opzok wsekaxrik velanc wxi cifeh og uqcaxgobk amfuq. Hiyeqk fkeaq kos naeyuxgie krim xx inhawumk fo royu money nazitb igzoyceov. Ej zge mopc ncucbit, cua’gz roig om e qiwozb nkae hojg tbavu tnrujsew pikiymedx: fre fafeqy diotxl pfuo.
Key points
The binary tree is the foundation of some of the most important tree structures. The binary search tree and AVL tree are binary trees that impose restrictions on the insertion/deletion behaviors.
In-order, pre-order and post-order traversals aren’t just important only for the binary tree; if you’re processing data in any tree, you’ll use these traversals regularly.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.