Problem Statement
You are given a pointer to the root of a binary tree. You need to print the level order traversal of this tree. In level order traversal, we visit the nodes level by level from left to right.
You only have to complete the function.
For example:
You only have to complete the function.
For example:
3
/ \
5 2
/ \ /
1 4 6
For the above tree, the level order traversal is 3 -> 5 -> 2 -> 1 -> 4 -> 6.
Input Format
You are given a function,
void level_order(node * root)
{
}
Output Format
Print the values in a single line seperated by a space.
Sample Input
3
/ \
5 2
/ \ /
1 4 6
Sample Output
3 5 2 1 4 6
Explanation
Level 1: 3
/ \
Level 2: 5 2
/ \ /
Level 3: 1 4 6
We need to print the nodes level by level. We process each level from left to right.
Level Order Traversal: 3 -> 5 -> 2 -> 1 -> 4 -> 6
Level Order Traversal: 3 -> 5 -> 2 -> 1 -> 4 -> 6
struct node
{
int data;
node* left;
node* right;
}*/
node** createQueue(int *front, int *rear){
*front = 0;
*rear = 0;
node** queue = (node**)malloc(sizeof(node*)*2500);
return queue;
}
void enqueue(node** queue, int* rear, node* element){
queue[*rear] = element;
(*rear)++;
}
node* dequeue(node** queue, int* front){
(*front)++;
return queue[*front - 1];
}
void LevelOrder(node * root)
{
int front,rear;
if(root == NULL){
return;
}
node* temp = root;
node** queue = createQueue(&front, &rear);
while(temp){
cout<<temp->data<<" ";
if(temp->left != NULL){
enqueue(queue, &rear, temp->left);
}
if(temp->right != NULL){
enqueue(queue, &rear, temp->right);
}
temp = dequeue(queue, &front);
}
}
No comments:
Post a Comment