二叉树层次遍历

/*given a binary Tree Level Order Traversal AC Rate: 950/3041 My Submissions
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},
	      3
	     / \
	    9  20
          /  \
	     15   7
 return its level order traversal as:
 	[
	  [3],
	  [9,20],
	  [15,7]
	]
*/

#include 
#include 
#include 
#include 


struct TreeNode
{
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x):val(x),left(NULL),right(NULL){}
};

class Solution
{
public:
	std::vector > levelOrder(TreeNode* root)
	{
		std::vector > vec;
		std::queue que;
		std::vector tem;
		int x=1;
		if(root==NULL)
			return vec;
		que.push(root);
		while(!que.empty())
		{
			int c=0;
			while(x--)
			{
				tem.push_back(que.front()->val);
				if(que.front()->left!=NULL)
				{
					que.push(que.front()->left);
					++c;
				}
				if(que.front()->right!=NULL)
				{
					que.push(que.front()->right);
					++c;
				}
				que.pop();
			}
			vec.push_back(tem);
			tem.clear();
			x=c;
		}
		return vec;
	}
};

你可能感兴趣的:(algorithm)