Answer to Question #284133 in C++ for tayyaba

Question #284133

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


1
Expert's answer
2022-01-02T02:20:23-0500
#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();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog