Trees
Level-Order Traversal
Visit a tree breadth-first with a queue.
Algorithm
The canonical tree is 4(2(1,3),6(5,7)), so this Kotlin DSA
implementation can be compared directly with the rest of the DSA track.
Basic Implementation
basic.kt
class Node(val value: Int, var left: Node? = null, var right: Node? = null)
fun render(node: Node?): String {
if (node == null) return "_"
if (node.left == null && node.right == null) return node.value.toString()
return "${node.value}(${render(node.left)},${render(node.right)})"
}
fun sampleTree() = Node(4, Node(2, Node(1), Node(3)), Node(6, Node(5), Node(7)))
fun listString(values: List<Int>) = values.joinToString(", ", "[", "]")
fun main() { val queue = ArrayDeque<Node>(); queue.addLast(sampleTree()); val output = mutableListOf<Int>(); while (!queue.isEmpty()) { val node = queue.removeFirst(); output.add(node.value); node.left?.let { queue.addLast(it) }; node.right?.let { queue.addLast(it) } }; println(listString(output)) }
Complexity
- Time: O(n)
- Space: O(w) queue space
Implementation notes
- Kotlin represents nodes with
class Node(val value: Int, var left: Node? = null, var right: Node? = null), so child links are nullable references. sampleTree()allocates the fixed root and children with nestedNode(...)constructor calls before traversal starts.- The traversal queue is
val queue = ArrayDeque<Node>(); the binding is not rebound, butaddLastandremoveFirstmutate the queue contents. - The root is enqueued with
queue.addLast(sampleTree()), so queue entries are non-nullNodereferences rather than nullable nodes. while (!queue.isEmpty())guardsqueue.removeFirst(), avoiding the empty deque exception path.- Output is collected in
val output = mutableListOf<Int>()withoutput.add(node.value)after each dequeue. - Child enqueue uses null guards:
node.left?.let { queue.addLast(it) }and the same forright, preserving left-before-right level order without enqueuing null sentinels. - The trace shows queue/output states
[4], then output[4]with queue[2, 6], then[4, 2]with[6, 1, 3], then[4, 2, 6]with[1, 3, 5, 7], ending at[4, 2, 6, 1, 3, 5, 7]and an empty queue. println(listString(output))formats the collected values as[4, 2, 6, 1, 3, 5, 7].
level order
Level-order traversal uses a queue to visit shallower nodes first.