I wrote a BFS to collect values level by level from a binary tree, but some leaf nodes never appear in the result. I suspect I’m mutating the queue incorrectly while iterating. What exactly is wrong here, and what’s the smallest fix?
function bfs(root) {
const q = [root], out = [];
for (let i = 0; i < q.length; i++) {
const node = q.shift();
out.push(node.val);
if (node.left) q.push(node.left);
if (node.right) q.push(node.right);
}
return out;
}
BayMax