I am trying to solve the leetcode problem 429. N-ary Tree Level Order Traversal
I have used the basic level order traversal concept as shown below
var levelOrder = function(root) {
let queue = [root, null];
let result = [];
let tmp = [];
for(let i=0; i<queue.length; i++){
let node = queue[i];
if(!node){
result.push(tmp);
tmp = new Array();
if(i !== queue.length-1) queue.push(null);
}else{
queue = [...queue, ...node.children];
tmp.push(node.val);
}
}
return result;
};
I tried running the sample Test-Cases Provided:
While submitting the same code I get to see the below error:
Can someone please explain what is going wrong here and what needs to be fixed?
The problem occurs when the test case passes an empty tree to your function, i.e. root
is null
.
In that case, the loop keeps adding null
values to the queue.
So add a null
check in your function:
if (!root) return [];