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) }
}
}