func levelOrder(_ root: TreeNode?) -> [[Int]] {
guard let r = root else {
return []
}
var queue: [TreeNode] = []
var queueB: [TreeNode] = []
var toBePrint = 0
var nextLevelCount = 0
var result: [[Int]] = []
var flag = true
queue.append(r)
toBePrint += 1
var temp = Array(repeating: 0, count: queue.count)
while queue.isEmpty == false {
let first = queue.removeFirst()
temp[flag ? (temp.count - toBePrint) : (toBePrint - 1)] = first.val
toBePrint -= 1
if let left = first.left {
queueB.append(left)
nextLevelCount += 1
}
if let right = first.right {
queueB.append(right)
nextLevelCount += 1
}
if toBePrint == 0 {
result.append(temp)
queue = queueB
temp = Array(repeating: 0, count: nextLevelCount)
toBePrint = nextLevelCount
nextLevelCount = 0
queueB = []
flag.toggle()
}
}
return result
}