Group Group Group Group Group Group Group Group Group

Implementation level-order traversal

#1

The current implementaion in the book is as follows:

public func forEachLevelOrder(visit: (TreeNode) -> Void) {
visit(self)
var queue = Queue()
children.forEach { queue.enqueue($0) }
while let node = queue.dequeue() {
visit(node)
node.children.forEach { queue.enqueue($0) }
}
}

What about just enqueing “self” and not handling the first case manually? seems easier to understand and shorter

public func forEachLevelOrder(visit: (TreeNode) -> Void) {
var queue = Queue()
queue.enqueue(self)
while let node = queue.dequeue() {
visit(node)
node.children.forEach { queue.enqueue($0) }
}
}

#2

@kelvin_lau Can you please help with this when you get a chance? Thank you - much appreciated! :]

#3

Looks like that could work. I’ll give it a test later and slot it in for the next version. Thank you for flagging this!