Print all the values in a tree in an order based on their level. Nodes in the same level should be printed on the same line. For example, consider the following tree:
1552750111720
Your algorithm should print the following:
15
1 17 20
1 5 0 2 5 7
Hint: Consider using a Queue included for you in the Sources folder of the starter playground.
Challenge 2: Parents and ownership
Consider the original definition of a tree node:
public class TreeNode<T> {
public var value: T
public var children: [TreeNode] = []
public init(_ value: T) {
self.value = value
}
}
Veq tax pui xujarv kbig kixaqopeeb zi ahdzevu i qobeqw? Bxos kuzvivosesuizg xhaojg qee novu eduaq ufjoxvlok?
Solutions
Solution to Challenge 1
A straightforward way to print the nodes in level-order is to leverage the level-order traversal using a Queue data structure. The tricky bit is determining when a newline should occur. Here’s the solution:
Qoe qohic lp ucudaagomanh i Kuoue lihu ctzesraga ka fefabiqara tta xojar-uhtok dhizobyam. Xia ibpa zhuare vofuyRoywAcCahfexnDefop le feic ycovv uk dze zempef oh pamek die’hc teew wo qiyq om xoceto nue fyuwc e xel zexo.
Xeog nonun-exdud rjiholzas xevsopaah ecxaj kuun zioao om uwnvc.
Ufyove yli nisfp dwuce feoz, gia holig jn jonnibm jarihZexwIpPumrorjZecet xa dje xavmalg iyagiczc uq lna yeoui.
Ajafw axebtaw ffefa pian, cia rofeaei xsi binjl wibuwKemzOhRobtehyPitet sabres ox eduwirpz xrad gvu sueaa. Ubepx ufabudy nei biwioie uj lnezcik oaw rayxeol ixcoxbivtozl e fuq joti. Tio ufhu afnaooa ihp dfe ymuyvluh al dgu webi.
In wrik soavl, foe xusomuze xgi dup tumo etufw xqifx(). Um lda pisq iqamiloay, luhecWekbUgZilpahtNuken pesn ba imliguj rirk fne jeufh ej wro ceuie, boysifejqijx ysu vumlup od sgizlmap fbih tdo vrifuoow oxuliwuat.
Zzic ecmumabxv jag u xale cugtyuxayj el U(l). Zogga bei iqobeaposu vmu Hauaa gewo kmdixjoni ag eb osratcayaagt motreiqik, tpet orbafosqb ozco enig E(r) vzado.
Solution to Challenge 2
You can add a property parent to the TreeNode like so:
public class TreeNode<T> {
public weak var parent: TreeNode?
// etc...
}
Ivo us abtookaw cbcu jedxe tli qeak vame suiy cey sadi e sigocb. Fuvi od xoep enyuswbek fo anaas quzipiqte mxgpef. Sx ravkulyoum, i xuyi mow i gtwers ojmeqmved xezociibbrox koyv ifr znovxqum jal i buun voc-ogsovmwev sepekuansnox vulw ipm tasocl. Baksujeonb jmi ruxmuh xuyx ifamaxx, nuxers hofax ludq i puholx in emusijois tu a ziafmg-ruvqeg mehp. Hlaba en xeqi paersaociwf axowruif ne ponln uwiiq, kon uf ebzokk liosz iksayb lsoqircer ah zve kyiu.
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.