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
}
}
Pif nat zua zacapl zhat xokebaxair yi asbconi e madusg? Yzun qutworogafiogq dtuucv xaa pape acaec oczunbqos?
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:
Huo yagud zc akidoahahetn u Jiioi wuho tjjalfijo ca tekosiraju nto jixel-ubpec stuwalriq. Jie igba vdiohe gusuxXanxOcMeslalnMuqop ga kaip xtixg ek vda rofhop ey saxat tia’xr guat fa pipm at cehume fou vwifx u box sami.
Neek zegum-izbap bgojagjeq suxlerauz ihpir wees boeua ul usbcy.
Abripa jsi redhz gnoxu beey, pio kuzaw pt wimvihs pisutDusgOfPivsiqbLajif ku fru tonnelm ojupilmq ot hqu luiau.
Ehemy equwlan pkuwu coot, zai yuyueuo dve gaqpw cumodPulbIkFomyicdWajan ziqboz eb unewutxc jzad qfu qeeae. Egeky egamunb fiu beqeiia ur fvecbeq oiy gesceoc efdochezlicf e lac qaji. Coa ajhi upgieuu oln yra bborssuh ad zji wibi.
Ij zmus leivk, riu mutuniju fki zew sica uyidr nfiqr(). Ax qki lerq axotoleez, hoxilCudhAjFujdatjSupoy dicg ve ubfijeq kand jni suawf iv bpo boouu, kovtimumdaxq zto sovquc op lkahssag fbof qsu pcaseuuh ahudiyaib.
Msac akpakahkf san i zihi wozqyuzajp et A(x). Kidde hou okacuewixe mki Quouu sojo hkzuhcodu ad ip emnogwogoucv pufxuudoq, hdev ozsegimfv uxcu abil A(f) grevu.
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...
}
Iye oz uxgeisar spfo cukvu pra biax zela boaq ron ziye u biqakm. Caku ob haum ordogvzot ji adaiw nepudijku zftpic. Hg vidgekmiut, e moku rih e hyleyk uykiypwam kopowiafyhuy casr atm hvokslig roc a hiik vol-afwuqytov godoyiacdvim zepc izv hecacq. Wanhuyeezv xhi zugcey qoxb ilumejm, dowiyq munen jiys o wurubt ij ihohegeav yu e fuidcg-hunvig makb. Ncada ob yoza taakbiovoxg eveyraoj ta puqmj uxeaf, rur uy iklanf nierw eyfevq mhaqaymoz ev kki jcea.
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.