Leetcode 429 - N-ary tree level order traversal

Note

  • Can be easily solved using level order traversal.

Example

img

1
2
Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/

/**
* @param {Node|null} root
* @return {number[][]}
*/
var levelOrder = function(root) {
let result = [];
if (!root) return result;
let queue = [root];

while (queue.length) {
let length = queue.length;
let curLevel = [];
for (let i = 0; i < length; i++) {
let node = queue.shift();
curLevel.push(node.val);
node.children && node.children.map(child => {
queue.push(child);
})
}
result.push(curLevel);
}
return result;
};