Binary Tree Write your own version of a class template that

Binary Tree Write your own version of a class template that will create a binary tree that can hold values of any data type. Demonstrate the class with a driver program. Your program should include:

Node Counter: Write a member function that counts and returns the number of nodes in the tree.

Leaf Counter Write a member function that counts and returns the number of leaf nodes in the tree.

Tree Height Write a member function that returns the height of the tree. The height of the tree is the number of levels it contains. For example, the tree shown in Figure 20-10 has three levels.

Tree Width: Write a member function that returns the width of the tree. The width of the tree is the largest number of nodes in the same level.

Code has to be in C++

Solution

#include <iostream>

using namespace std;

template <class T>
class BinaryTree{
private:
   struct Node{
       T val;
       Node *left;
       Node *right;
       int height(){
           int h = 0;
           if(left != NULL){
               h += 1 + left->height();
           }
           if(right != NULL){
               h += 1 + right->height();
           }
           return h;
       }
       int nodeCount(){
           int count = 1;
           if(left != NULL){
               count += left->nodeCount();
           }
           if(right != NULL){
               count += right->nodeCount();
           }
           return count;
       }
       int leafCount(){
           int count = 0;
           count += left == NULL ? 1 : left->leafCount();
           count += right == NULL ? 1 : right->leafCount();
           return count;
       }
   };
   Node *root;
public:
   BinaryTree(){
       root = NULL;
   }
   int height(){
       return root == NULL ? 0 : root->height();
   }
   int nodeCount(){
       return root == NULL ? 0 : root->nodeCount();
   }
   int leafCount(){
       return root == NULL ? 1 : root->leafCount();
   }
};

int main(){
   BinaryTree<int> bTree;
   cout << bTree.height() << endl;
   cout << bTree.nodeCount() << endl;
   cout << bTree.leafCount() << endl;
   return 0;
}

Binary Tree Write your own version of a class template that will create a binary tree that can hold values of any data type. Demonstrate the class with a driver
Binary Tree Write your own version of a class template that will create a binary tree that can hold values of any data type. Demonstrate the class with a driver

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site