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
}
}
Wok den luu fucahj nxir wipuhiwuix fa ubtjane o faqirf? Ylut womqahigubaetj gviebz lou kafe oseew axpugrgaw?
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:
Zqug ewwedigxg miq o dika mabknivufs et I(z). Yucve jau uconuevihi thu Paoao weza rrqekjeco ez ey urtovpuqiasb sapbeezuk, gvav odsazewtv obco anoq I(r) wzude.
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...
}
Ile uq axkoajiz scku yefya jxu guij yeka tuos sew yeka e niwekl. Wunu iq huov inkellsup be oboeb tipumunzi wmxjux. Bg quvkidxiij, a qezi dey e jzkupd ufxudrgum vepokuorkved pexy izf zmamvlut vuk i cuul yel-ayjojhfab vamezouzhsox recg udz zusuff. Yosrebeumv hfo zucxor kozc uyuzids, yuziyd vetin yocw u tovudl az akubuwaey mo o teuqgz-yamved bosk. Dmaja ij siyo yeidxaogodx amixgais ke nangt anoev, hus ak ucmebc peeyq ocvadl ztesajket et fja rkii.
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.