Skip to content

Instantly share code, notes, and snippets.

@vrat28
Last active May 20, 2021 08:07
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 vrat28/5f6b82d67c36e36722c3467e390ae5aa to your computer and use it in GitHub Desktop.
Save vrat28/5f6b82d67c36e36722c3467e390ae5aa to your computer and use it in GitHub Desktop.
Binary Tree Level Order traversal
class Solution {
func levelOrder(_ root: TreeNode?) -> [[Int]] {
guard let root = root else { return []}
var queue = [TreeNode]()
var output = [[Int]]()
queue.append(root)
while queue.isEmpty == false {
// start new level
// number of elements in the current level
var levelCount = queue.count
var levelNodes = [Int]()
while levelCount > 0 {
let node = queue.first!
queue.removeFirst()
levelCount -= 1
levelNodes.append(node.val)
// Add Left child node
if let left = node.left{
queue.append(left)
}
// Add right child node
if let right = node.right{
queue.append(right)
}
}
// Add nodes by level
output.append(levelNodes)
}
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment