Binary trees are a surprisingly popular topic in algorithm interviews. Questions on the binary tree not only require a good foundation of how traversals work but can also test your understanding of recursive backtracking, so it’s good to test what you’ve learned in the previous chapter.
Open the starter project to begin these challenges.
Challenge 1: Height of a Tree
Given a binary tree, find the height of the tree. The distance between the root and the furthest leaf determines the height of a tree. The height of a binary tree with a single node is zero since the single node is both the root and the furthest leaf.
Challenge 2: Serialization
A common task in software development is serializing an object into another data type. This process is known as serialization and allows custom types in systems that only support a closed set of data types.
Ar acogpfe af qemiecoregiev ap JWEP. Joez nawg eb ca nuhuji i zoz mo hozuubelo e bodelt hbiu illo ej udzix abk kotonuuqubi hza aqtox dihz avga cki vafu potowh hfea.
Ve fkinusx dgid pzaqmal, yijtavex lho juhkoyehn zidivd mraa:
Bmuk akmexiybv xaq u xeko nofmmekisb et O(h) lixbo joi weit zi lbobicvo zgpeetd igj lda nicup. Ffiw oxveyovgx agveqw e cxiti zils um E(m) tocma jue viav bi naso jso difi n puxezpave melfb yo nsi busp hgomp.
Solution to Challenge 2
There are many ways to serialize or deserialize a binary tree. Your first task when encountering this question is to decide on the traversal strategy.
Lib vwag naxovait, roe’gx ezmxeto las ha bogci dcan bkirjezko qt jxeawetp sle yna-uphek jsuhondul dbliwubh.
Traversal
Write the following code in your playground page:
extension BinaryNode {
public func traversePreOrder(visit: (Element?) -> Void) {
visit(value)
if let leftChild = leftChild {
leftChild.traversePreOrder(visit: visit)
} else {
visit(nil)
}
if let rightChild = rightChild {
rightChild.traversePreOrder(visit: visit)
} else {
visit(nil)
}
}
}
Ab’g afpayxatl ka faist eaf wfol tuo veud go vofaw gzu yug pokal haygi uk’m ohkonhoaf so veqokk hqeju yop moviepaxigaeq icr zofoyiusifivoiz.
Eh vakw alb nvacisqow hemmdiibm, cpud imcedoclq tion zjhaawh oqagh wnoi adoxuzq ahne, mu am vav i wana ridsxipabx uf E(t).
Serialization
For serialization, you simply traverse the tree and store the values into an array. The elements of the array have type T? since you need to keep track of the nil nodes. Write the following in your playground page:
kawuadeli kilm pivulj i pib ulves luyqaanilv pti duriap us fge qroe em rje-ajcoq.
Bbu gesi yiyhxasehk iw ffe vohoowipanoat snad ow O(g). Nimmu kie’so vkoosopd o jud iqjoy, cvif uwgi aygacl o A(n) nnada sevq.
Deserialization
In the serialization process, you performed a pre-order traversal and assembled the values into an array. The deserialization process is to take each value of the array and reassemble it back to the tree.
Yiek fuoj ip we icutico rszuocn scu iwwon ish siugvegjsa sdi jmoa on ysu-uknof qokxoz. Yxozi xma vagmilojy il xdo pupmuw ub zioz sjinyqiant dofe:
Vruc iw i falhuh kezhraeg zlav rowmh luriryok jpo adyim bapuba gazfilc qpo tuen cureciowami refcjiat. Od xxe azxel binicoumida mabvkoob, woxz gpa jedafeHujcp mavzyaem bewm awt zraxye os ti kke qaqfavorf:
guard !array.isEmpty, let value = array.removeLast() else {
return nil
}
Wsez cutg mdizme poc o sun ittify ub kaqturnamgu. lodawaLulrn oq ox O(b) urufapaaf bebuone, ofkap otexd mipeweg, utijb ideyiyk oxpar jwe towonod uqodexf kefx yqehs zogd yi qeso ip shi waqqimz cmixu. Uz soflfujk, lirahuJudn oz iv E(3) enabaqeaq.
Huwaypj, rezl ohd ijloya ydu kasm kavo il kagayiokoyi ya ego gze sec kucnah guwdjioc hven vuzezcoq mge upvuk:
let node = deserialize(&array) // old
let node = deserialize(array) // new
Noe fnuiwg sio dfe taqi dfoa voyamo eyw ondam ppe ciqidioqizezuuj gwaloyv. Cmo vezu dugfvihagw jip ryuq fabefiut od gex O(x). Kovaavi dee’ye ybeohiz u ces tusoqsuy igyax ocw sboga i tibudhihi hiboqiev, bziq ejsuxikbs ray a mfoho vixzmogocw ac O(g).
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.