Loading…
Loading…
Breadth-first: visits the tree one level at a time, left to right, using a queue.
Level-order: visit the tree row by row (BFS).
Output: []
1void levelOrder(Node root) {2 Queue<Node> q = new LinkedList<>(); q.add(root); // Start queue with the root3 while (!q.isEmpty()) { // Until the queue drains4 Node node = q.poll(); // Take the front node5 out.add(node.val); // Visit this node6 if (node.left != null) q.add(node.left); // Enqueue left child7 if (node.right != null) q.add(node.right); // Enqueue right child8 }9}