Function to find the size of Binary Tree

1.using recursion: size of binary tree =(size of left child+1+ size of right child).


static int sizeOfBinaryTree(treeNode * rootNode) {

	//size = size of left tree + 1 + size of right tree
	if (rootNode == NULL)
		return 0;
	else
		return sizeOfBinaryTree(rootNode->leftChild) + 1
				+ sizeOfBinaryTree(rootNode->rightChild);

}

2.Non-recursive approach :


static int sizeOfBinaryTreeWithoutRecursion(treeNode * rootNode) {
	int count = 0;

	// create a Q which store pointer of treeNode object
	queue<treeNode*> Q;

	//add first element to Q
	Q.push(rootNode);

	while (!Q.empty()) {  //till queue is not empty
		treeNode * temp = Q.front();
		Q.pop();
		count++; //increase count by 1
		if (temp->leftChild) //if node have left child then add it to Q
			Q.push(temp->leftChild);
		if (temp->rightChild)  //if node have right child then add it to Q
			Q.push(temp->rightChild);
	}
	return count; //size of tree
}

above mention function is member function of my Tree ADT class you can check complete program here

A Developer
Gy@n!

About Gyaneshwar Pardhi

Exploring the world and trying to know how can i involve to make this perfect. Gy@n!
This entry was posted in Algorithm, c++, Data Structure, interview Question, Programming and tagged , , , . Bookmark the permalink.

Leave a comment