this is C++ please lable files !! Write the definition of the function,nodecount
ID: 3867256 • Letter: T
Question
this is C++
please lable files !!
Write the definition of the function,nodecount,that returns the number of nodes in the binary tree.add this function to the class birnaryTreeType and create a program to test this function
Write the definition of the function,leavescount ,that takes as a parameter a pointer to the root of a binary tree and returns the number of leaves in a binary tree. Add this function to the class binaryTree Type and create a program to test this function
Write a function, swapSubtrees,that swaps all of the left and right subtrees of a binary tree add this function ti the class binarytreeType and create a program to test this function
Explanation / Answer
Since the question does not give the existing code, I assume the you have a struct to represent a node in binary tree and the name is node. Also assuming you already have the binaryTreeType in .h and .cpp file separated. You will need to add the code given below into there respective files. In case your struct for node is having a different name, please use the correct name as you have it. You can post a comment in case you need any help. If the answer helped, please do rate it . Thank you.
FILE: binaryTreeType.h
class binaryTreeType
{
//other variables and functions
public:
int nodecount();
int leavescount();
void swapSubtrees();
private:
int nodecount(node* n);
int leavescount(node* n);
void swapSubtrees(node *n);
}
FILE: binaryTreeType.cpp
//other functions...
int binaryTreeType::nodecount()
{
return nodecount(root);
}
int binaryTreeType::leavescount()
{
return leavescount(root);
}
void binaryTreeType::swapSubtrees()
{
swapSubtrees(root);
}
int binaryTreeType::nodecount(node* n)
{
if(n == NULL) return 0;
return 1 + nodecount(n->left) + nodecount(n->right);
}
int binaryTreeType::leavescount(node* n)
{
if(n == NULL) return 0;
if(n->left == NULL && n->right == NULL)
return 1;
else
return leavescount(n->left) + leavescount(n->right);
}
void binaryTreeType::swapSubtrees(node *n)
{
if(n == NULL) return;
node* temp = n->left;
n->left = n->right;
n->right = temp;
swapSubtrees(n->left);
swapSubtrees(n->right);
}
FILE: binaryTreeTester main()
main()
{
///.....other calls on binaryTreeType to insert delete etc
cout << "The number of nodes in the tree are " << tree.nodecount() << endl;
cout << "The number of leaves in the tree are " << tree.leavescount() << endl;
tree.swapSubtrees();
cout << "The tree after swapping subtrees is " << endl;
tree.inorder(); //call the inorder traversal on the tree
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.