Print Left View of a Binary Tree

Below is a function which uses two queues which stores the current and next nodes value for printing left view of a binary tree. when we are swapping elements from next nodes queue to current node queue just print from element from the Q2 i.e. first node of each level.


static void printLeftViewOfBinaryTree(treeNode *rootNode) {

	//queues to store current and next level nodes
	queue<treeNode*> Q1;
	queue<treeNode*> Q2;

	Q1.push(rootNode);

	//print rootNode node
	cout << rootNode->val << endl;

	while (!Q1.empty()) {

		treeNode * temp = Q1.front();
		Q1.pop();

		if (temp->leftChild)
			Q2.push(temp->leftChild);
		if (temp->rightChild)
			Q2.push(temp->rightChild);

		if (Q1.empty() && !Q2.empty()) {
			//print the first element of each level
			cout << Q2.front()->val << endl;
			//move nodes form next level to current level
			swap(Q1, Q2);
		}

	}

}

above mention function is member function of my Binary 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 c++, Data Structure, interview Question, Programming and tagged , . Bookmark the permalink.

Leave a comment