Write the definition of the function, nodeCount, that returns the number of nodes in a binary tree. Add this function to the class binaryTreeType and create a program to test this function
#include<iostream>
#include<string>
using namespace std;
struct Node
{
int data;
Node* left;
Node*right;
Node(int _data):data(_data),left(NULL),right(NULL){}
};
class binaryTreeType
{
Node* Head;
public:
binaryTreeType():Head(NULL){}
void insert(int value)
{
Node* p = new Node(value);
Node* parent = NULL;
if (Head == NULL)
{
Head = p;
}
else
{
Node* temp = Head;
while (temp != NULL)
{
parent = temp;
if (value > temp->data)
temp = temp->right;
else
temp = temp->left;
}
if (value < parent->data)
parent->left = p;
else
parent->right = p;
}
}
int nodeCount()
{
return nodeCounttemp(Head);
}
int nodeCounttemp(Node* p)
{
static int count = 0;
if (p != NULL)
{
nodeCounttemp(p->left);
count++;
nodeCounttemp(p->right);
}
return count;
}
void Display()
{
Print(Head);
}
void Print(Node* p)
{
if (p != NULL)
{
Print(p->left);
cout << " " << p->data << " ";
Print(p->right);
}
}
};
int main()
{
binaryTreeType bt;
bt.insert(4);
bt.insert(1);
bt.insert(5);
bt.insert(9);
bt.insert(8);
bt.insert(6);
bt.insert(11);
bt.insert(3);
bt.insert(2);
bt.Display();
cout << "\nNumber of Nodes is " << bt.nodeCount();
}
Comments
Leave a comment