BFS Level-order Python / Scala
Python\n\nfrom collections import deque\n\nclass Solution:\n    def levelOrder(self, root):\n        # Corner case.\n        if not root:\n            return []
> Python\n```\nfrom collections import deque\n\nclass Solution:\n    def levelOrder(self, root):\n        # Corner case.\n        if not root:\n            return []\n        \n        nodes = []  # Result nodes.\n        nodeDeque = deque([root])  \n        # BFS on tree using nodeDeque.\n        while nodeDeque:\n            levelLen = len(nodeDeque)\n            levelNodes = []\n            for i in range(levelLen):\n                curNode = nodeDeque.popleft()\n                levelNodes.append(curNode.val)\n                if curNode.left:\n                    nodeDeque.append(curNode.left)\n                if curNode.right:\n                    nodeDeque.append(curNode.right)  \n            nodes.append(levelNodes)\n            \n        return nodes\n```\n> Scala\n```\nimport scala.collection.mutable.Queue\nimport scala.collection.mutable.ArrayBuffer\n\nobject Solution {\n    def levelOrder(root: TreeNode): List[List[Int]] = {\n        // Corner case.\n        if (root == null) {\n            return List()\n        }\n        \n        val queue = new Queue[TreeNode]() \n        val resultList = new ArrayBuffer[List[Int]]()  // List of values of treenodes in the final result.\n        val levelList = new ArrayBuffer[Int]()  // List of values of treenodes within a level.\n        \n        // BFS level-order traversal.\n        queue.enqueue(root)\n        while (!queue.isEmpty) {\n            val size = queue.size\n            levelList.clear()\n            for (i <- 1 to size) {\n                val curNode = queue.dequeue()\n                levelList.append(curNode.value)\n                if (curNode.left != null)  queue.enqueue(curNode.left) \n                if (curNode.right != null)  queue.enqueue(curNode.right)\n            }\n            resultList.append(levelList.toList)\n        }\n        \n        resultList.toList\n    }\n}\n```\n**(\u4EBA \u2022\u0348\u1D17\u2022\u0348)** Thanks for voting!
[]