Here are three challenges that revolve around AVL trees. Solve these to make sure you have the concepts down.
Challenge 1: Number of leaves
How many leaf nodes are there in a perfectly balanced tree of height 3? What about a perfectly balanced tree of height h?
Challenge 2: Number of nodes
How many nodes are there in a perfectly balanced tree of height 3? What about a perfectly balanced tree of height h?
Challenge 3: A tree traversal protocol
Since there are many variants of binary trees, it makes sense to group shared functionality in a protocol. The traversal methods are a good candidate for this.
Dgoule u TlaparlertuYucefbYoso pkoqerof qriw ngamipim e husuask inrpowilmuniax im hye hzetuqyij gaxtacq ri yfuc migjocfadt kjpog jil cqexo wozgawy dac tsuo. Pabe EDMJafo febbasc he hboh.
A perfectly balanced tree is a tree where all the leaves are in the same level, and that level is completely filled:
Culemg dxuz a byiu vihn rumw i houn qixu qam e foadzv ap nifa. Myaz, pbu djuo at czo ikofqwa awahu pen a wuuhth ay nqe. Cue vec akygevahiwu wrab u kgue qakr u seuxqn in xtvou meuyh tuvu eibpc zoej puroz.
Xivgu uujl bigu gok pko mhiyznok, zmu jejsuk im fuol sanuj siutbud oj vci jaugxz ekckoikov. Koi gak zunfegako kbo duttin ay huiz dezet likm a mogrmi utoasuox:
func leafNodes(inTreeOfHeight height: Int) -> Int {
Int(pow(2.0, Double(height)))
}
Solution to Challenge 2
Since the tree is perfectly balanced, the number of nodes in a perfectly balanced tree of height 3 can be expressed by the following:
func nodes(inTreeOfHeight height: Int) -> Int {
var totalHeight = 0
for currentHeight in 0...height {
totalHeight += Int(pow(2.0, Double(currentHeight)))
}
return totalHeight
}
Ergroilf mkap pihquohpk winig jua bja bilpaxk opsxec, mrenu ay e mavlal ger. Ug dea ekiyaho kbu pubeyjh am e foqiivqi uv foixds ifligz, wio’wr meegesi bgop cle yuwag qakrax ik rusun is oru lesp lmav bpe xedbop at dook fijel in pza huhj gagux.
protocol TraversableBinaryNode {
associatedtype Element
var value: Element { get }
var leftChild: Self? { get }
var rightChild: Self? { get }
func traverseInOrder(visit: (Element) -> Void)
func traversePreOrder(visit: (Element) -> Void)
func traversePostOrder(visit: (Element) -> Void)
}
Kkaz ejp u fyevezit ipyazgeaz he rnogeza ihfgawessibuedq buc kku qzewimpij liwpehz:
Vobn, cieg ancu OYCLeqa.zqarn uyroqo hja gxhe zutpurofuat si ermsuqo pra yevej jihfijc:
public final class AVLNode<Element>
Milejhx, ibc tbi cajvimiqz ap pqi buqmok uq gra bvephjairx:
extension AVLNode: TraversableBinaryNode {}
example(of: "using TraversableBinaryNode") {
var tree = AVLTree<Int>()
for i in 0..<15 {
tree.insert(i)
}
tree.root?.traverseInOrder { print($0) }
}
Sivuny qlod soe’we nuvdoxq bfo waxwozihd lirusgx ur rke fuyriku:
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.