suibenzhi
4/15/2018 - 6:22 AM

c++ 二叉树打印.cpp

#include <iostream>
#include <vector>
#include <queue>


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


class TreePrinter {
public:
	vector<vector<int> > printTree(TreeNode* root) {
		
		vector<vector<int> > vec_Print;
		queue<TreeNode*> que_Temp; 
		if(NULL == root)
			return vec_Print;
		
		TreeNode *last;
		TreeNode *nlast;
				
		last = root;
		nlast = NULL;
		que_Temp.push(last);

		vector<int> vec_Temp;

		while(que_Temp.size() != 0)
		{
			
			if(NULL != que_Temp.front()->left)
			{
				que_Temp.push(que_Temp.front()->left) ;
				nlast = (que_Temp.front()->left);
			}
			
			if(NULL != que_Temp.front()->right)
			{
				que_Temp.push(que_Temp.front()->right);
				nlast = (que_Temp.front()->right);
			}
			
			vec_Temp.push_back(que_Temp.front()->val);
			
			if(que_Temp.front() == last)
			{
				last = nlast;
				vec_Print.push_back(vec_Temp);
				vec_Temp.clear();
			}
			
			que_Temp.pop();	

		}
		
		vector<int>().swap(vec_Temp);
		return vec_Print;
	}
};