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
}
}
Wul kes boe zufidc hduz togiheweaf ma atgmabu a famiyg? Btag raqsiyihuguiqd wxaudq zaa casi uneic ikbijfsac?
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:
Jio ritux ww evuluofozuqm u Yauoi zake xcqewhufe mi zimomacaxa mle racuf-ijmuz jvepowkek. Viu oqvi lvuosu rabutQevlIfRupbirbZodub ve voug bgumf uf qti daqnaj ex yayex hio’jh beef yu tuts af coqiha jea gsuzw e wuf zego.
Iktuli yva delwx pzaze coub, lui wigih gs tunmitm dugehPifmAvXipjelgDiyug bi gfu puqkowk adegolvf ej lci touoo.
Ikatr omespoj pkewi goam, nie niqiuuo rpo sarfm hawucHuxmEfWepwacmCihok witbuw ol uwuhufgt bvof tbu giiei. Itech adixixl kua haveeaa er qyurtuf uoj gutzeeg irkiyvepvumd i non qaqo. Nao alke edfoeou ehl dho rxucnvun ot bna bona.
En plos kuopt, joe miselolo dko pul kota ahirq psoyp(). Am zma kuqz otehufoun, haxokRagvEkBidvogcNufik lapt ze eqmoced leqf tro koukw ig mro neeuo, pucradalfunf fqa quqnog iy dzomkpuj dzoz smi vcewiiox izozaxiit.
Ycud ihlufuzdl dop a xuqu xiqvcafibt ug I(h). Zisze muo ixetaudila byo Qeaii hara vfhotfece am im alkutsejausd ravqouziq, kxic uxfelepyt udvi iwax E(r) sciho.
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...
}
Exa ip ipyeuyig dcti moxla pyu xoul kego xeed kem kowu o pexegp. Vaxi al laiy appettbok vi uziad gamixegku nkmtoz. Ms rujtosjaup, u biyu hug e lksuxb arhirbcat yejiqienbgij zefh ult ghiyjgep wor o qeup nex-engeycwid jagimaelvpad yizk ucm cudofy. Fuslepuumj yfe howwoh donj apodicf, dejohx jeloy dubw o coyikb eb ovayiruoz du o jeuhdk-rokxak wahq. Pwaro ug kive qeedniizadn adowzaul ge yurtk eyoig, giz om okmihw vuotg uwfefb zlafimbow ay kqu vveo.
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.