Problems178
Search for a command to run...
Breadth-first search (BFS) on a tree using a queue
Current step
Start Level Order Traversal (BFS) using Queue. Initialize empty queue.
Breadth-First Search (Queue)
1function levelOrder(root) {2 const ans = [];3 if (!root) return ans;4 //size: —level: []5 const q = [];6 q.push(root);7 8 while (q.length > 0) {9 const size = q.length;10 const level = [];11 12 for (let i = 0; i < size; i++) {13 const node = q.shift();14 level.push(node.data);15 16 if (node.left !== null) q.push(node.left);17 if (node.right !== null) q.push(node.right);18 }19 20 ans.push(level);21 }22 23 return ans;24}