Question: Write a C++ program that creates a tree from given input, and prints the leaf nodes using the level-order traversal. The following is how we
Write a C++ program that creates a tree from given input, and prints the leaf nodes using the level-order traversal.
The following is how we define tree nodes:
struct node
{ int item; node *l, *r;
node(int x)
{ item = x; l = 0; r = 0; }
};
typedef node* link;
The trees for this assignment have the following properties:
1)Each node has zero, one, or two children (left child and right child);
2)Each node has a unique key. That is, the item in each node is different from items in all other nodes.
3)Each input item is also unique.
You may find the following function useful. This function visits nodes in a tree in level order starting at the given root h using a QUEUE (you can use any implementation for QUEUE):
void traverse(link root, int n)
{
link h;
QUEUE q(n);
q.put(root);
while (!q.empty())
{
h = q.get(); // get link h at the head of the queue
if (h->l != 0) q.put(h->l);
if (h->r != 0) q.put(h->r);
}
}
Your program will receive the following input and do the following for each input:
C
L
R
P: Print the items in nodes in a level order traversal manner
S
See the example dialogue below:
C 5
Root node with item 5 has been created
C 10
Error: Tree is not empty
L 5 3
Node with item 3 has been added
R 5 4
Node with item 4 has been added
P
level order traversal of the entire tree: 5 3 4
S 4
Level order traversal of the asked subtree: 4
L 4 7
R 7 8
R 3 9
L 9 11
R 4 12
L 7 13
S 3
level order traversal of the asked subtree: 3 9 11
S 4
level order traversal of the asked subtree: 4 7 12 13 8
L 8 14
R 12 15
R 8 16
L 13 17
P
level order traversal of the entire tree: 5 3 4 9 7 12 11 13 8 15 17 14 16
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
