# Implementation level-order traversal

**URL:** <https://forums.kodeco.com/t/implementation-level-order-traversal/55273>\
**Category:** Data Structures & Algorithms in Swift\
**Created:** [November 12, 2018, 4:32pm UTC](https://forums.kodeco.com/t/implementation-level-order-traversal/55273 "2018-11-12T16:32:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ivangodfather](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/ivangodfather/32/81494_2.png) [@ivangodfather](https://forums.kodeco.com/u/ivangodfather)\
**Post date:** [November 12, 2018, 4:32pm UTC](https://forums.kodeco.com/t/implementation-level-order-traversal/55273/1 "2018-11-12T16:32:47Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![shogunkaramazov](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/shogunkaramazov/32/108826_2.png) [@shogunkaramazov](https://forums.kodeco.com/u/shogunkaramazov)\
**Post date:** [November 12, 2018, 7:09pm UTC](https://forums.kodeco.com/t/implementation-level-order-traversal/55273/2 "2018-11-12T19:09:45Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kelvin\_lau](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/kelvin_lau/32/109371_2.png) [@kelvin\_lau](https://forums.kodeco.com/u/kelvin_lau)\
**Post date:** [November 16, 2018, 3:47pm UTC](https://forums.kodeco.com/t/implementation-level-order-traversal/55273/3 "2018-11-16T15:47:53Z")

</div>

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!
