I am looking for algorithm to do BFS in O(n) for n-ary tree, I found the following algorithm, but I have a problem in analysing the time complexity. I am not sure if it's O(n) or O(n^2). Can someone explain the time complexity or give an alternative algorithm which run in O(n)
Thanks
breadthFirstSearch = (root, output = []) => {
if (!root) return output;
const q = new Queue();
q.enqueue(root);
while (!q.isEmpty()) {
const node = q.dequeue();
output.push(node.val);
for (let child of node.children) {
q.enqueue(child);
}
}
return output;
};