Swift: Lean Code , Recursion & Iteration by Martin R
\n# Recursion with A nested function\n\n\n\n\n\n\n\nfunc levelOrder(_ root: TreeNode?) -> [[Int]] {\n    var levels: [[Int]] = []\n\n    func recursiveVisit(_ n
\n# Recursion with A nested function\n\n\n```\n\n\n\n\nfunc levelOrder(_ root: TreeNode?) -> [[Int]] {\n    var levels: [[Int]] = []\n\n    func recursiveVisit(_ node: TreeNode?, level: Int) {\n        guard let node = node else {\n            return\n        }\n        if level < levels.count {\n            levels[level].append(node.val)\n        } else {\n            levels.append([node.val])\n        }\n        recursiveVisit(node.left, level: level + 1)\n        recursiveVisit(node.right, level: level + 1)\n    }\n\n    recursiveVisit(root, level: 0)\n    return levels\n}\n```\n\n\n# Iteration\n```\nfunc levelOrder(_ root: TreeNode?) -> [[Int]] {\n    guard let root = root else {\n        return []\n    }\n\n    var wrapList: [[Int]] = []\n    var queue = [root] // First level\n\n    while !queue.isEmpty {\n        // All values of nodes on the current level:\n        wrapList.append(queue.map { $0.val })\n        // Replace queue by list of all nodes on the next level:\n        queue = queue.flatMap { [$0.left, $0.right ] }.compactMap { $0 }\n    }\n\n    return wrapList\n}\n```\n\n\n\n\n[more info](https://codereview.stackexchange.com/questions/213423/swift-syntax-102-binary-tree-level-order-traversal/213453#213453)
[]