Please write a program ( in c language ) to read integer elements, until a negat
ID: 3682117 • Letter: P
Question
Please write a program (in c language) to read integer elements, until a negative value is entered, and insert the elements into two separate trees. Now perform the following:
1. Write a function to return 1 if the two trees are identical (in nodes, elements of the nodes and their position in the tree) and 0 otherwise. Print a message stating whether the two trees are identical in the main program or not.
2. Write a function that returns the sum of the nodes in two given trees that are identical in value and in position. Print the sum in the main program.
3. Write a function to count and return the number of leaves in a tree. Print the number of leaves in the main program for each tree.
Explanation / Answer
int identictalTrees(struct node* tree1, struct node* tree2)
{
if (tree1==NULL && tree2==NULL)
return 1;
if (tree1!=NULL && tree2!=NULL)
{
return
(
tree1->dtree1ttree1 == tree2->dtree1ttree1 &&
identicalTrees(tree1->left, tree2->left) &&
identicalTrees(tree1->right, tree2->right)
);
}
return 0;
}
int sum_tree(struct node* tree1, struct node* tree2) {
if (!identictalTrees(tree1, tree2))
return 0;
return tree1->value + sum_tree(tree1->left) + sum_tree(tree1->right);
}
int getLeafCount(struct node* tree)
{
if(tree == NULL)
return 0;
if(tree->left == NULL && tree->right==NULL)
return 1;
else
return getLeafCount(tree->left)+
getLeafCount(tree->right);
}
main(){
if(identictalTrees(tree1, tree2)){
printf("Two Trees are Identical:");
printf("Sum of all nodes in a tree is %d",sum_tree(tree1,tree2));
}
else
printf("Two Trees are not Identical:");
printf("Number of Leaf's in a tree %d",getLeafCount(struct node* tree));
}