Skip to content

Instantly share code, notes, and snippets.

@tifoaudii
Created June 9, 2021 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tifoaudii/06e6b1fd8e64c247e9aca4ae0742291b to your computer and use it in GitHub Desktop.
Save tifoaudii/06e6b1fd8e64c247e9aca4ae0742291b to your computer and use it in GitHub Desktop.
extension TreeNode {
public func levelOrderTraversal(visit: (TreeNode) -> Void) {
visit(self)
var queue = [TreeNode]()
children.forEach { queue.append($0) }
while !queue.isEmpty {
let node = queue.removeFirst()
visit(node)
node.children.forEach { queue.append($0) }
}
}
}
let tree = createTree()
tree.levelOrderTraversal {
print($0.value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment