PLEASE C++ ONLY all 3 should yield to one solution (so one program) 1. Write the
ID: 3866597 • Letter: P
Question
PLEASE C++ ONLY
all 3 should yield to one solution (so one program)
1. Write the definition of the function, nodeCount, that returns the number of nodes in the binary tree. Add this function to the class binaryTreeType and create a program to test this function.
2. Write the definition of the function, leavesCount, that takes as a parameter a pointer to the root node of a binary tree and returns the number of leaves in a binary tree. Add this function to the class binaryTreeType and create a program to test this function.
3. Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Add this function to the class binaryTreeType and create a program to test this function.
Explanation / Answer
#include <iostream>
struct nodeType
{
elemType info;
nodeType<elemType> *llink;
nodeType<elemType> *rlink;
};
class binaryTreeType
{
public:
int treeNodeCount(struct node* node)
{
if (node==NULL)
return 0;
else
return(size(node->left) + 1 + size(node->right));
}
int getLeafCount(struct node* node)
{
if(node == NULL)
return 0;
if(node->left == NULL && node->right==NULL)
return 1;
else
return getLeafCount(node->left)+ getLeafCount(node->right);
}
void swapSubtreeNodes(Node *root, int k)
{
int level =1;
if (root== NULL || (root->left==NULL && root->right==NULL) )
return ;
if ( (level + 1) % k == 0)
Swap(&root->left, &root->right);
swapSubtreeNodes(root->left, level+1, k);
swapSubtreeNodes(root->right, level+1, k);
}
void inorder(Node *root)
{
if (root == NULL)
return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
/* create a program to test this function*/
int main()
{
/*create a tree*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Size of the tree is %d", treeNodeCount(root));
getchar();
printf("Leaf count of the tree is %d", getLeafCount(root));
getchar();
int k = 2;
cout << "Before swap node :"<<endl;
inorder(root);
swapSubtreeNodes(root, k);
cout << " After swap Node :" << endl;
inorder(root);
return 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.