Print a BST Level by Level With a Queue
Print a BST Level by Level With a Queue
Complete printLevels() so it prints the tree one level per line, from the root down. On each line the values go from left to right, separated by single spaces. An empty tree prints (empty), and that part is already written.
Reminder: level-order traversal uses a queue. In-order, pre-order and post-order all dive down one branch before coming back up. Level-order reads the tree row by row instead, top to bottom and left to right, like lines on a page. A queue does this naturally because it is first in, first out: take a node off the front, put its children on the back, and those children wait until every node already in the queue has had its turn.
8 <- level 1
/ \
4 12 <- level 2
/ \ / \
2 6 10 14 <- level 3To put each level on its own line, look at how many nodes are in the queue at the start of a pass: that is exactly one whole level. Remove exactly that many, adding their children to the back as you go, then print the line.
Requirements:
1. Keep the provided start: the empty-tree check, the Queue<Node> built from a LinkedList, and offering root.
2. Loop while the queue is not empty. Each pass handles one level and prints one line.
3. Use poll() to take a node from the front and offer() to add a node to the back, and only offer children that are not null.
4. Build each line in a StringBuilder with no trailing space.
The Node class is provided - do not rename it and do not add public to it, because a Java source file may contain only one public class.
Do NOT write a main method.
Expected Output:
50 30 70 20 40 60 80 35
= newline. The output ends with a newline — print one after the last line.
Your Output
Run your code to see the output here...