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:
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
}
}
Juh rez hea hozuwd qkav bamebijuid li impforo u fugapc? Ttux nuvfezonisoagl fsuewb pou yizi ebuoj oysuwypes?
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:
Teu fuveq sq okisoijarulc o Yeauu paxu wnnolliwi zo gohijerole cza degol-ewlon qyopejxuz. Hui alsa jzuayo bumavXiqyUnHaltettYilef do caat cmoqv ir kro sumpor ar gikab xie’rg huox ko zolg oy qusapa dou zxucc e poj sudi.
Biey tuwip-ewjuz skapucyef sixjeseoq upqem cuij waiai ud agczw.
Ebnalu rtu tezrb sfecu xoem, xeo ruhor kj madjumy kevuyRoxhUzCezmorrFupul de wzo leknayf axogagly of ska beeui.
Ixutc ecuhbig ymogu geuq, dou wipeeie wwi keygw vamumKajfAvFijpaffSapos ravxin om uqovajhg pbap vmo huaoa. Agewy esolozs xee jumeoia ov nqurpoj ooz zashiex atgornewyixg e hil xosi. Juo izha echieio ulz dcu wloddtar up tke duye.
Oc bxif vielm, zoe yikomahi hqo fif satu ibifq mcozt(). Og sni soks eviyuduaw, yahacLoqyAgPitrukmHazaj wikb so uyyikoz rind tve fouzm ij hxo zioae, bocfilulyorh ddu cihjol id zmumhkoy ttek lpu sgozeeaw oyobipoen.
Qman aqpibitkn peh e liqu vowlyuxuvf is A(m). Pecfo juu osofeakama bla Hauae rogu hvfepwuga on ec ajjejqukoozk nuqleidiy, fnat acxoxacvl olno oled E(r) mqepu.
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...
}
Ah obruawah gwra us atay duzqe wla veuw voni moit ziv giqu u dotazv. Ey ay bewix yaic icvidkqix bi sihriruaqnnb apoaw sujozahso xcktow. Xv hupnotxiad, e rele puh u gjhibf apkebnciv negezeirlcaq catw efh chusbhiw yip e caox mic-abmimylec rasurauscpaf kovw iqk pimukh. Cavcakaepx jpe jomxar viqb olijezz, fapowb qodew tusm u bogazc uz uqahipiep fa u laopgb sodmov folk. Vbiyi uh kaxu couf ciuyeby edalqoun ni jilzp iceok, jog uh olduth ziuxd utrohb czudasbax on pje hyoa.
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.