Last active
May 20, 2021 08:07
-
-
Save vrat28/5f6b82d67c36e36722c3467e390ae5aa to your computer and use it in GitHub Desktop.
Binary Tree Level Order traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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