Please write a single program with the classes given below and a test for them.
Write the define of the function, net count, that returns the number of nodes in the binary tree. Add this function to the class binary tree type and create a program to tract this function. Write the define of the function leaves count, that takes as a parameter a points to the root node of a binary tree and returns the number of leaves in a binary tree. Add this function to the class binary tree type and create a program to test this function. Write a function, swap sub trees, that swaps all of the left and right sub trees of a binary tree. Add this function to the class binary tree type and create a program to test the function.
Expert Answer
#include<iostream.h>
//using namespace std;
/* node declarations*/
struct node{
int info;
struct node *left;
struct node *right;
}*root;
/* Class declarations */
class BST{
public:
insert(node*,int);
nodeCount(node *); //node count method
leavesCount(node *);//leave count method
BST(){
root=NULL;
}
};
int main(){
int num;
BST bst;
bst.insert(root,1);
bst.insert(root,2);
bst.insert(root,3);
bst.insert(root,4);
/*create a tree*/
int nCount = bst.nodeCount(root);
cout<<“node count of tree is “<<nCount;
int lCount = bst.leavesCount(root);
cout<<“leaf count of the tree is “<<lCount;
//getch();
return 0;
}
// insert method
void insert(node *root, int d){
if(root== NULL){
root = new node;
root->info = d;
root->left=NULL;
root->right=NULL;
return;
}
if(root->info== d){
return;
}
if(root->info > d){
if(root->left !=NULL){
insert(root->left,d);
}
else{
root->left->info =d ;
(root->left)->left =NULL;
(root->right)->right =NULL;
return;
}
}
else{
if(root->right !=NULL){
insert(root->right,d);
}
else{
root->right->info = d;
(root->left)->left =NULL;
(root->right)->right =NULL;
return;
}
}
}
// leaves count method
int leavesCount(struct node* node){
if(node==NULL){
return 0;
}
if(node->left==NULL &&node->right==NULL){
return 1;
}
else{
return leavesCount(node->left)+
leavesCount(node->right);
}
}
// node count method
int nodeCount(struct node* node){
if(node ==NULL){
return 0;
}
else{
return 1+nodeCount(node->left)+
nodeCount(node->right);
}
}