[原题链接](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/solution/qian-duan-shi-tang-ti-jie-chao-hao-li-ji-u2td/) ## 队列 bfs 使用队列进行广度优先遍历,level 数组存放当前层级的值,处理完一层后推入结果数组 result。 ```javascript const levelOrder = function(root) { if (root == null) return [] const result = [] const queue = [root] while (queue.length > 0) { const levelSize = queue.length const level = [] for (let i = 0; i < levelSize; i++) { const head = queue.shift() for (const child of head.children) { queue.push(child) } level.push(head.val) } result.push(level) } return result } ``` - 时间复杂度:O(n) - 空间复杂度:O(n)
Activity