Wirte a program to create tree with 5 element and display them in level order traversal
Answers
Answer:
Print level order traversal line by line | Set 1
Given a binary tree, print level order traversal in a way that nodes of all levels are printed in separate lines.
For example consider the following tree
Example 1:
Output for above tree should be
20
8 22
4 12
10 14
Example 2:
1
/ \
2 3
/ \ \
4 5 6
/ \ /
7 8 9
Output for above tree should be
1
2 3
4 5 6
7 8 9<
Note that this is different from simple level order traversal where we need to print all nodes together. Here we need to print nodes of different levels in different lines.
A simple solution is to print use the recursive function discussed in the level order traversal post and print a new line after every call to printGivenLevel().
/* Function to line by line print level order traversal a tree*/
void printLevelOrder(struct node* root)
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
{
printGivenLevel(root, i);
printf("\n");
}
}
/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level)
{
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
Answer:
Print level order traversal line by line | Set 1
Given a binary tree, print level order traversal in a way that nodes of all levels are printed in separate lines.
For example consider the following tree
Example 1:
Output for above tree should be
20
8 22
4 12
10 14
Example 2:
1
/ \
2 3
/ \ \
4 5 6
/ \ /
7 8 9
Output for above tree should be
1
2 3
4 5 6
7 8 9<
Note that this is different from simple level order traversal where we need to print all nodes together. Here we need to print nodes of different levels in different lines.
A simple solution is to print use the recursive function discussed in the level order traversal post and print a new line after every call to printGivenLevel().
/* Function to line by line print level order traversal a tree*/
void printLevelOrder(struct node* root)
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
{
printGivenLevel(root, i);
printf("\n");
}
}
/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level)
{
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
..
..