This is an interview question
I think of a solution. It uses queue.
public Void BFS()
{
Queue q = new Queue();
q.Enqueue(root);
Console.WriteLine(root.Value);
while (q.count > 0)
{
Node n = q.DeQueue();
if (n.left !=null)
{
Console.Writeln(n.left);
q.EnQueue(n.left);
}
if (n.right !=null)
{
Console.Writeln(n.right);
q.EnQueue(n.right);
}
}
}
Can anything think of better solution than this, which doesn't use Queue?
I tweaked the answer so that it shows the null nodes and prints it by height. Was actually fairly decent for testing the balance of a red black tree. can
also add the color into the print line to check black height.
Try with below code.
Let's see some Scala solutions. First, I'll define a very basic binary tree:
We'll use the following tree:
You define the tree like this:
We'll define a breadthFirst function which will traverse the tree applying the desired function to each element. With this, we'll define a print function and use it like this:
Now, Scala solution, recursive, lists but no queues:
Next, Scala solution, queue, no recursion:
That recursive solution is fully functional, though I have an uneasy feeling that it can be further simplified.
The queue version is not functional, but it is highly effective. The bit about importing an object is unusual in Scala, but put to good use here.
C++:
Input :
Balanced tree created from:
Output:
Algorithm:
P.S: I know the OP said, no queue. My answer is just to show if someone is looking for a C++ solution using queue.
Since the question requires printing the tree level by level, there should be a way to determine when to print the new line character on the console. Here's my code which tries to do the same by appending NewLine node to the queue,