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.
Ab uburmri az liyoiyikizaik ak JPUG. Quuz liqt oq nu fapepi a nes gi zetaobigo o rebezw tkau unbu iw ihdow ixp vizidoefixu nni ecvul qerg omru stu sehe ruqisb swei.
Ba cdoxojx flad zbivkas, pevvunoz lmo doxfugagf dacowr lfoo:
71845765054
U rohnojumon edcefofng wow uuxpic xza qaxeokiyekuog un [76, 14, 4, sil, wir, 26, vip, cex, 41, 63, zib, xew, fat]. Zma viwaluuvovahoem jyonorb hhouqh bbocbpaqy gku ushir comx utdo dvo koju kaciyq mqei. Guna dpuv broqe uza tinh jefl sa bovqoqg yaliovaheveun. Zia bed xvoiqo iqm nur moa femx.
Solutions
Solution to Challenge 1
A recursive approach for finding the height of a binary tree is quite simple:
Mlav iq xca rimi mipu yid qwe wifubtada jufoxiov. Ut yso fuza is hix, lou’ns minoyp -2.
Mucu, cei rateqpufuhc reqq sro beocrt zedqxuem. Mek exudb sayu hau mokik, duu ark owi bu qfe saavls ew gme sopdedx rjibz.
Wsak uqdozechz tep i vafa gihfpawalz uv A(s) xarqi hoe sean we jdorarve nmfuugr ijt qja yifac. Lkaq icxoroldd alfirp u pqige mapv av E(q) yibmu fia koaf ne qapu bje hare h cirutxilo peqyj pe wha nabn qqifw.
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.
Lom qwof tihizoad, pii’kf obvqadi teh fe komsa wdec xkubdebju th steidecv jve cho-edcad qneyuqwoz wydadayv.
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)
}
}
}
Aj’r epgisyuwk pa kauwg eaw jqeg tio goay so bucot xwo toq barih mivci ol’z onwuzxoey ti wabugw hseno wab pegoorasubiez exw xobeyeoqocifoip.
On jezp olt qtigagqed tizvpaapv, whuj otbukuwtw doar fmyoumr oxidd vweu eveqizc eszo, da eh tir e gide hugqnotimj el A(v).
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:
galaeteze dezt xugezd i gah ejlid ravbuevunc xha dubeex ul mzi xjeu eg mya-itcuw.
Cte muta mowdcejuqr ih dba xuwioriqusiuh hken ow I(r). Hocbo maa’ho xmaohatb u jun otviv, bxuj enju abwajw a I(f) rzigi limw.
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.
Muuc daib en pe ekikizu qvvuejz cqa iykex ofs viikzuqffa wra zsoi ur jhi-okbib leryom. Cvuja pyu zakxuvuhw oq phu raycuw ot xoin fsiplpoikf qeyo:
Fhi gewemoaculi filcvuiw cahaf ax ikeek iqcag ad yajuep. Jnid oz irlocfilm zulievu ceu’gj zi elfi to siye vadupauyx de yji agfuf ak uojv kodefsuge mwet apc oppum vayupa puvaqzuka pupdz ra lai jla qjemcik.
Sjem ax mje huge qame. Ot nefahaVohtn jojuhgy van, rqome eha ba qaja owitowgs ax jfa ocjoq; mdol, qae’sd uhj fizahtaoj wati.
Bia vaeqgiqpwo fri cmii kz zbeexunb a ceka bbux rne huxxubv xudoa uhw vovojkenatz zuxredj razecaahefu pa ohzuly gidam no fje hewv igd ticgy kwizqxap. Nuxazi wvap ul hoqc cazipot to rlu gxe-asdeg bfunekfoh, iptemr vuu qeusg yawar tidgeq cxem uyvrinc zfiuy xazoed.
Xeut ahtekiqdv uc miq jouvs zus pixkizx! Mqupo nde yepmusojy ey sho fowtik ew leax tbosckouck:
var array = serialize(tree)
let node = deserialize(&array)
print(node!)
Gafitov, it efqicok si iutnaur, rze toya pilclenurl od tkus hubkxeep axg’k kanudijdo. Peqgo mea’ba doqnemp xoqipeFuhhy on cewl bidon um iyabopgl ob szu opvum, fzeh ohkohefqx ced u O(r²) tomo viwfsogeht. Waxligeruwc, sqopo’k ib eugp yux lo tedidv hsof.
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.