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 Swift DSA
implementation can be compared directly with the rest of the DSA track.
Basic Implementation
basic.swift
final class Node {
let value: Int
var left: Node?
var right: Node?
init(_ value: Int, _ left: Node? = nil, _ right: Node? = nil) { self.value = value; self.left = left; self.right = right }
}
func render(_ node: Node?) -> String {
guard let node = node else { return "_" }
if node.left == nil && node.right == nil { return String(node.value) }
return "\(node.value)(\(render(node.left)),\(render(node.right)))"
}
func sampleTree() -> Node {
return Node(4, Node(2, Node(1), Node(3)), Node(6, Node(5), Node(7)))
}
func listString(_ values: [Int]) -> String { return "[" + values.map(String.init).joined(separator: ", ") + "]" }
var queue: [Node] = [sampleTree()]
var output: [Int] = []
while !queue.isEmpty { let node = queue.removeFirst(); output.append(node.value); if let left = node.left { queue.append(left) }; if let right = node.right { queue.append(right) } }
print(listString(output))
Complexity
- Time: O(n)
- Space: O(w) queue space
Implementation notes
final class Nodeuses reference semantics withlet value: Intand optional child linksleft: Node?andright: Node?.var queue: [Node] = [sampleTree()]stores node references in a mutable Swift array; the initial queue contains the root4.var output: [Int] = []records visited values separately from the queued nodes.- The traversal loop runs while
!queue.isEmpty, then useslet node = queue.removeFirst()to dequeue the front node. On SwiftArray, front removal shifts remaining elements and is linear in the queue length. - Each visited node appends
node.valuetooutput, thenif let leftandif let rightunwrap optional children beforequeue.append(...). - The trace shows the queue by node values:
[4], then[2, 6], then[6, 1, 3], then[1, 3, 5, 7], and finally drains to[]. - The output grows in level order as
[4],[4, 2],[4, 2, 6], and ends at[4, 2, 6, 1, 3, 5, 7]. listString(_:)formats theIntarray with comma separators, soprint(listString(output))writes[4, 2, 6, 1, 3, 5, 7].
level order
Level-order traversal uses a queue to visit shallower nodes first.