Quantcast
Viewing all articles
Browse latest Browse all 34

Print all nodes of the same level from binary tree

Print all nodes of the same level from binary tree. For example the output for the below binary tree is 6,8,5,8,3.

Image may be NSFW.
Clik here to view.
Print all nodes of the same level from binary tree

C++ Print all nodes of the same level from binary tree

#include <iostream>
#include<queue>
#include<vector>
using namespace std;

typedef struct Tree
{
		struct Tree* left;
		struct Tree* right;
		int data;
} TreeNode;

TreeNode* make_node(int data)
{
	TreeNode* tmp = new Tree();
	tmp->data = data;
	tmp->left = NULL;
	tmp->right = NULL;
	return tmp;
}
void levelOrder(TreeNode* root)
{
	queue<TreeNode*> q;
	if (!root) return;

	q.push(root);
	while (!q.empty())
	{
		vector<int> tmp;
		int len = q.size();
		for (int i = 0; i < len; i++)
		{
			TreeNode* t = q.front();
			tmp.push_back(t->data);
			q.pop();
			if (t->left)
			{
				q.push(t->left);
			}

			if (t->right)
			{
				q.push(t->right);
			}
		}
		for(unsigned int i=0; i < tmp.size();i++)
			cout << tmp.at(i) <<" ";
	}
}

int main()
{
	TreeNode* root= make_node(6);
	root->left = make_node(8);
	root->right = make_node(5);
	root->right->left=make_node(8);
	root->right->right=make_node(3);
	levelOrder(root);

	return 0;
}

 

The post Print all nodes of the same level from binary tree appeared first on wikistack.


Viewing all articles
Browse latest Browse all 34

Trending Articles