- Write a function that will print all the elements from a binary tree in the bracketed form (data: LT, RT) where data is the element in the root, LT denotes the left subtree of the root printed in bracketed form, and RT denotes the right subtree in bracketed form. For example, the following tree
will be printed as
$\texttt{(6: (2: (1: , ) , (9: , )) , (8: , ))}$ - Modify the function so that it prints nothing instead of (: , ) for an empty subtree, and x instead of (x: , ) for a subtree consisting of only one node with the Entry x. Hence the preceding tree will now print as $\texttt{(6: (2: 1 , 9) , 8)}$.
Difficulty level
This exercise is mostly suitable for students
void print1(Btree B)
{
if(B)
{
printf("(%d: " , B->data);
print1(B->left);
printf(" , ");
print1(B->right);
printf(")");
}
}
void print2(Btree B)
{
if(B)
{
if(B->left && B->right)
{
printf("(%d: " , B->data);
print2(B->left);
printf(" , ");
print2(B->right);
printf(")");
}
else
printf("%d" , B->data);
}
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Heap of prime factors