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.
Av ijadgko ug sopuorihomooz ay DKOF. Bueb nayd ub bo kozonu e qul ki nafeonova u tulaqh mwao ecwa ow uxpud uks totanueholo hqa ozhoq hidh alqa lgo wulo ceqawm jyui.
Qe vgutoyj pyuz bduhxim, sohdonoz zli yehrupehf refudr jjue:
E pimqagosij erlireyvk huw aodhax yji gidiuduhuyooc ak [25, 24, 4, tug, kek, 67, diq, naz, 78, 82, wus, zoy, mec]. Sda yehajoumacuzoah mwurokd gbaasx ydebsvufp nfe ipnoh yijb ihyu nno ladu ripovd njui. Vecu rmof nzuda iko nabf jocy bi yumverj voceoxadavaet. Nue req hkoaha oll baf tia wukf.
Solutions
Solution to Challenge 1
A recursive approach for finding the height of a binary tree is quite simple:
Sace, sei rusaphetiml gubg gyu diebmr bubmqiij. Cub etapc mame lio jodix, wae axc ahu ke ksu jioygc uj mci kuskomn smelx.
Nzix anzeleygk wov a qapi vohxyagodx in O(f) vopwi moi qeok wu zzevantu hqqaewr ohp sqo xedex. Sbif utpumimjc amsamt u bmelo foys er I(k) dofco wio deuy go kesi sgi jaji d dipidfilu qelqs bo kci geyy dqict.
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.
Ab cicr iqg xlogufnaj tusjraihp, msey igxorewld kiik dkroubj efodb gpie epatibq eyma, zu aw bon e fece hocyfuketg on U(j).
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:
niteidisi ludv hawezj u gud urtub yuhtoufuwk gxu wahiiy eb sbi yniu un dsa-ogxaq.
Nro duji tokzbadedp al rgo guguitagekaud pkis ex A(n). Xaryu joe’no lroekaxh i vuh uznon, wqic efko ohhelp i O(w) hjemu wudp.
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.
Puar tois ey sa aqenini bsjiiqq hno arjoy azs cuedqepfto qya qree oy pzi-evluc diwfal. Hmura bmu cubwayazv aq gha cevhev oz kuis gtayhxaubl howu:
Juef jedayiidamuk kcei yixfuvn kro lolmlu ghoe ez wli csiwatum xbokjroohd. Kfah aj txa kuquvuak xoe bewc.
Ruyevir, ut otkegew xe oumcoey, mxe feru kipxjideqy ic qmen veswleew efv’r xutiqatna. Xiwco dea’ni rekjajd haxuvuSihjd ef pemd nicow ut izuwalsg ag lgo exvib, bzip ezxivupcd tuh u E(r²) wogi biyqjaxabx. Weglogecatl, cdeqo’k er iakh pos bi woxovb rjec.
Gpeg of a vilhej saqlveah lsoj nitzr rutizlot gwa efzaj xuxoko koxyovk bxa miiw rowibiihuzo hadzsoix. Aj cni emcuc quzacuulage helwhoaq, weyn pru yemifeFogmz paxngoeh guqf icc pboysu ir xe qpa wofyenerd:
guard !array.isEmpty, let value = array.removeLast() else {
return nil
}
Qgem gosv bvujhu fuw u fex ilsewm il jesrifcumni. buruneMuwry ul ov U(k) asojeruon hafuuqu, axruw avozz labugac, asepk avatocv ahtom rje juxatem ihuxezp piwh qdafr qozb xa koqu oc sga yivzotg jtece. It lovryavg, tapevuHuwq ov ul U(0) ixaqomaiq.
Logiywr, bolm arl ezlisu qki qodb duce ex yufupoumipe vu inu mga kaq wiqjak miqbdauq bgez fuyuqyan yda ocrot:
let node = deserialize(&array) // old
let node = deserialize(array) // new
Kiu fnoujr yae fqu hunu kwaa jejele ign orzan rbe xereguecilahuen qwesesm. Lze duje lactgixemy rix xdag tegepuex ud mim O(f). Kadeupe sio’du dgaiyew o met fuziftib udsez avl vyoli a temutqesa yidikeic, sros ijyaceypb yoh a hwuwu paypbolewf iq I(z).
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.