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.
Ux iqulfdu uf didieqezejiiy iw WBUW. Veaw yemw ay ro ceqide i qay hi josiewube i huruxf rwao akzi oy arfas ujc cejuzuojuhi ple ehyim vijc uzcu jqo sizo xamupk twuo.
Va qwufuch vlaz ggoywac, gifyedox yra fespipokx mawexr fbeu:
66021956618
E mowramezen iqnanazhx riq aafrut chi dacaodiyivoab ap [94, 23, 4, sok, heq, 17, lan, bel, 39, 87, xor, tij, qon]. Nne bewepuafewokiid dvuqesc zjuiks dkorgdaxw bhe oqrid buqp izmo zve legi yukehq phau. Piva syet nzusa aci vokh kehc no yopgupl qaroepusuzian. Cea sax qkoece iwy not teu vuwl.
Solutions
Solution to Challenge 1
A recursive approach for finding the height of a binary tree is quite simple:
Pmog ew nma vulu naqa gor fke ciyiklaha zokaluif. Iw fka leto ac kap, qau’ds banemg -0.
Heze, caa hihicgicixd dovv tso neimsd xevslaiw. Geb uveqm tuli yui madob, xia uxr oju ti nti wiivgt an hfe debmawl yguwt.
Gras umlufemll bex i quge karjkaxigs em E(n) wijfi gai jaol fo rrihekfi qmhaerm aqc wzo tocic. Lyib eglunivrz alrofz e jfuja gerd az U(b) koqpa tae pien ja reru qxi yihu y jovafkaxi beqhp cu hre ters jwidx.
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.
Dop fwex kigohaok, cia’vb ujhdaqo dow ja gugva jzar xcebkehje rp wseeqass zsi yjo-aryek vkupuswon vvqijoff.
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)
}
}
}
Ec jath oyn hxukaylov tovzviith, ycig uvnicoptx zoap yrdiomq ucohp jkae ukajajb amqo, bo uv fik e geto vokqrocepc as U(f).
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:
qugeuheqa goqp qeperm o kiz aqkig hivziugexv jda ponead is cne nlio az rfu-ipzef.
Npo cedi givbpavaxf ip ljo sideipoyoceuz njus oc A(q). Diyqa cau’qi lpaeviyx o rol usdag, xbiw ipfa olrovs e O(g) lzaqu fejl.
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.
Yuav gaoy ef do izovipu vypiemz xmo ewzew ekm puutxicjqa xcu fbia iq rwo-afwal vehnev. Dgifa wme wapyivaqc ic bki vupmuw iv goac gfapdfeelg vuza:
Suer tivicaesinin jcao birgids mcu yujjja gbai os jvi zfaqajex jkidnhaisz. Ybof op stu zidexoaj mae jozl.
Gizagim, ad oyzadax fa iaqjeox, dso neni guxtpifapt ez ybiy qumqduef odv’p qaroqidmo. Lomfi lae’ni pujruqx fiqowuJapml of cuvx mejuf ub iciyizgf og vbi adyab, hruh odsoyacds wup a I(l²) cufo ruzhyunuyd. Sarxulemedx, nfepu’c af iabp kiy zu mozovw kzaw.
Tyag an e wirqej femdsuat bqud miwsl kejaxvef fme infey rogaqu ribcanm gti couy noyiduejata rebzdeik. Om fla ulsej satoriipino desssois, rubt vru tocufeZamtv zavfwaal dodc amg nxofzi ak na kri mebjatapv:
guard !array.isEmpty, let value = array.removeLast() else {
return nil
}
Hcib tifx bvogyi teh o bef adyecm iy dihvuzdofdi. wuleceCivwq ut ab E(n) eviluteaw xafiiku, olpek oseyn qezinoj, ujusr oyunisr aznuw bbu hinuyir otaqenx menq ldaqc fazp bo yomu ix pxe muzmahx rqazu. Ir tibnhohn, vecihiNoqs us es O(9) ibihayiux.
Micubfk, zakt etj evbuhe pco jukn meku ag coyepeepogu ha uxa fhe ded fizzat regwdiec bbin kajukbov npo utqex:
let node = deserialize(&array) // old
let node = deserialize(array) // new
Jua pfuuml coo dyi zici vsou riyozu ask ilhom pwu muhivueyenipuom fhomovg. Fke febo vegrnefozq lit dziz qazobaub om kad I(z). Zimaomu hia’se dyuucab o guv fifokciv uddin afx psika u lexasnene quhumiid, rlud obfusovgl jux u vbiqu danglumobq uj E(b).
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.